Post <Li> Items with Json and Jquery to Web Method - c#

I am trying to pass a <li> list to a web method using json and Jquery. My goal is to return this list to C# using a Session Variable.My problem is that the session return always null. So the list never passes on Web Method.
The List:
<div>
<ol id="mycart">
<li>iPhone</li>
<li>iPod</li>
<li>iPad</li>
</ol>
</div>
<input type="button" id = "btngetCart" value="Get cart" />
The Json Script:
<script type="text/javascript">
$("#btngetCart").live("click", function () {
var items = $('.mycart').find('li').map(function() {
var item = { };
item.title = $(this).text();
return item;
});
var json = JSON.stringify(items);
$.ajax({
type: 'POST',
url: "WebForm4.aspx/GetCart",
data: "{json}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (r) {
}
});
});
</script>
The Web Method:
public class mycart
{
private string[] title;
}
[WebMethod(EnableSession = true)]
public static mycart GetCart(mycart title)
{
HttpContext.Current.Session["j"] = title;
return title;
}

Error here :
html : <ol id="mycart"> has id attribute
var items = $('.mycart') //used class, which does not exists, try this:
var items = $('#mycart')
AND change
data: "{json}",
to
data: json,

Related

Fetching Cities dynamically in Asp.net HTML control

I have a HTML dropdown list for countries. Now I want to populate the City dropdown accordingly using ajax
<select class="form-control" id="ddCountry" runat="server" tabindex="8"></select>
<select class="form-control" id="ddCity" runat="server" tabindex="9"></select>
<script type="text/javascript">
$('#ddCountry').on('change', function () {
var storeData = { countryId: this.value }
$.ajax({
type: "POST",
url: "UserRegistration.aspx/GetCities",
data: JSON.stringify(storeData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("The data in list is "+data);
},
error: error
});
});
</script>
My method on .cs page is as follows:
[WebMethod]
public static List<CityBO> GetCities(string countryId)
{
//returning cities
}
The problem is I am able to fetch the data in GetCities method but not able to show it in the ddCity list because it is a HTML control and the method is static, so
ddCity.Items.AddRange(list_of_countries) is not working as ddCity is not being recognized in static method. Please tell how to fill the dropdown list.
You cannot access controls in static method. You need to return list of cities from webmethod and fill dropdown using javascript.In success method of ajax write code like this.
success: function (data) {
fillDropDown(data.d);
}
function fillDropDown(data){
var html = "";
for (var i = 0; i < data.length; i++)
{
html += "<option value='" + data[i].ValueField+ "'>" +
data[i].TextField+ "</option>";
}
$("select[id$=ddlCity]").html(html);
}
You can use ajax success function given below.
success: function (data)
{
var lankanListArray = JSON.parse(data.d);
// running a loop
$.each(lankanListArray, function (index, value)
{
$("#ddlCity").append($("<option></option>").val(this.name).html(this.value));
});
}

Returning Json Data From Controller to View ASP.NET MVC

I am trying as the title says to return a Json message from the Controller to the View after it validates.
I have made a breakpoint, and I know that the code works from Controller side, and that my JavaScript calls with success the ActionResult now. How do I display that message in the View?
There are two buttons, stamp in and stamp out. If the user stamps in twice, it should get a message, same with stamp out. I have two ActionResults who are indentical except some message and string changes.
Controller:
[HttpPost]
public ActionResult CreateStamp(Stamping stampingmodel)
{
var validateMsg = "";
stampingmodel.Timestamp = DateTime.Now;
stampingmodel.StampingType = "in";
if (stampingmodel.User == null || ModelState.IsValid)
{
var idValidated = db.Users.Find(model.UserId);
if (idValidated != null)
{
var stamp =
db.Stampings.Where(s => s.UserId == stampingmodel.UserId)
.OrderByDescending(s => s.Timestamp)
.FirstOrDefault();
if (stamp.StampingType == stampingmodel.StampingType)
{
if (stampingmodel.StampingType == "in")
{
validateMsg = "Stamped Twice In A Row!";
}
}
else
{
if (stampingmodel.StampingType == "in")
{
validateMsg = "Stamped In, Welcome.";
}
}
}
db.Stampings.Add(stampingmodel);
db.SaveChanges();
}
return Json(new {Message = validateMsg });
JavaScript:
$(document).ready(function () {
$("#stampInBtn").click(function () {
var userId = $("#userId").val();
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: {
userId: userId,
}
});
});
View:
<input type="text" id="idUser" class="form-control" />
<br />
<input type="submit" value="IN" id="stampInBtn" />
I have more code inside the View of course; divs, head, body, title and scripts. But it's perhaps a little irrelevant.
What should I do to successfully show those messages?
Regards.
Add a success function to the ajax call
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: { userId: userId },
success: function(data) {
// data contains the value returned by the server
console.log(data);
}
});
So if the controller returns
return Json("This is a message");
the value of data will be "This is a message". Note the return value can be a complex type or a partial view
You are getting the value of $("#userId"), but your input has an id of idUser.
Try making your input:
<input type="text" id="userId" class="form-control" />
Also it would be a good idea to provide your Stamping model structure as it seems that you only pass the user id in your post and nothing else.
Change your javascript code as following:
$(document).ready(function () {
$("#stampInBtn").click(function () {
var userId = $("#userId").val();
$.ajax({
url: "ComeAndGo/CreateStamp",
type: "POST",
dataType: "json",
data: {
userId: userId,
},
success: function(data) {
var objData= jQuery.parseJSON(data);
alert(objData.Message );
},
error: function (request, status, error) {
alert(request.responseText);
}
});
});
});

Fill DropDownList with JsonData

I haven't worked on Json before,its my first time and as expected I stucked at a point where I want to fill the DropDown with the JsonData.
Here What I am doing is I have an Xml which I am converting in Json like:
string xml = "<Root><Name>A</Name><Name>B</Name><Name>C</Name></Root>";
Then doing this to convert it into JsonString:
XmlDocument doc = new XmlDocument();
doc.LoadXml(Xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
Currently my View is like:
<div>
<input type="button" value="work" name="work" id="idwork" />
</div>
#Html.DropDownListFor(x => x.Name, new SelectList(Enumerable.Empty<SelectListItem>()), new {id="ddl_items" })
Script:
var ddl = $('#ddl_items');
$('#idwork').on('click', function () {
$.ajax({
url: url,
data: {},
type: 'post',
contentType: 'application/json; charset=utf-8',
success: function (myJSONdata) {
$(myJSONdata.Name).each(function () {
ddl.append(
$('<option/>', {
value: this.ReworkTunnelName
}).html(this.Nome)
..
..
});
Now what I want to do is Fill the Dropdown with Names with the help of this JsonData.
please help
$.each(myJSONdata, function ()
{
ddl.append($("<option></option>").attr("value", this.ReworkTunnelName).text(this.Nome));
});
Edit
$.each(myJSONdata, function ()
{
ddl.append($("<option></option>").attr("value", this.ReworkTunnelName).attr("text",this.Nome));
});
$.each(myJSONdata.Root, function ()
{
ddl.append($("<option></option>").attr("text", this.ReworkTunnelName));
});
You can create a new javascript function and pass the dropdown id and json data as parameters in it.
Then you can parse json data as per your data structure. Further run a loop and add items in the select element.
you can use getJSON method in jQuery :
$.getJSON("ActionMethodName", "", function (data) {
$(data).each(function () {
$("<option>").val(this.ReworkTunnelName)
.text(this.Nome)
.appendTo("#ddl_items");
});
});
HTML :
<select id="ddl_items">
<option></option>
</select>
I end up doing this and this is working Fine..
$('#idRework').on('click', function () {
$.ajax({
url: url,
data: {},
type: 'post',
contentType: 'application/json; charset=utf-8',
success: function (myJSONdata) {
var obj = jQuery.parseJSON(myJSONdata);
$.each(obj.Root.ReworkTunnelName, function (index, itemData) {
ddl.append($('<option></option>').val(itemData).html(itemData));
});
}
});
});
Try this
$.each(myJSONdata, function (index, item) {
$('#ddl_items').get(0).options[$('#ddl_items').get(0).options.length] = new Option(item.Text, item.Value);
});

How to prevent duplicate entries in Jquery Sortable connection list?

i have two asp dropdown list.. based on the values selected in two dropdown list it will generate two unordered list dynamically in which i have implemented Jquery Sortable connection list.. The first list contains some default values.. I need to drag and drop the required values to the second list... It should prevent adding duplicate entries..
I am pasting my code below... Kindly check that and provide me a solution:
This is the aspx code for two dropdownlist:
<form id="form1" runat="server">
Application <asp:DropDownList ID="ApplicationList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="FetchRoleFromApplication" >
</asp:DropDownList>
Role <asp:DropDownList ID="RoleName" runat="server" onchange="javascript:ShowSortable();" >
</asp:DropDownList>
<ul id="sortable1" class="connectedSortable" runat="server" style="display:none">
</ul>
<ul id="sortable2" class="connectedSortable" style="display:none" runat="server" >
</ul>
</form>
The first ul list is independent so its values is loaded in the codebehind(pageload) like this:
HtmlGenericControl li;
JavaScriptSerializer objJSSerializer = new JavaScriptSerializer();
foreach (FetchUserGroup_Result objectItem in Allusergroup)
{
li = new HtmlGenericControl("li");
li.ID = objectItem.group_id.ToString();
li.Attributes.Add("class", "ui-state-default");
li.InnerText = objectItem.group_name;
sortable1.Controls.Add(li);
}
The second ul list values are loaded by an ajax call like this...
function ShowSortable() {
$('#sortable1').show();
var postJSONData = JSON.stringify({ ApplicationId: $('#applnhdnname').val(), RoleName: $('#RoleName').val() });
$.ajax({
type: 'POST',
data: postJSONData,
url: 'UserManagementService.svc/GetUserGroupsForApplicationRole',
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function success(response) {
$("#sortable2").append(response.d);
$('#sortable2').show();
},
error: SessionExpiryHandler
});
}
The corresponding wcf service is this:
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
public string GetUserGroupsForApplicationRole(string ApplicationId, string RoleName)
{
User user = new User();
JavaScriptSerializer objJSSerializer = new JavaScriptSerializer();
List<GetUserGroupForApplicationRole_Result> usergroup;
usergroup = user.GetUserGroupForApplicationRole(ApplicationId, RoleName);
string sample = string.Empty;
foreach (GetUserGroupForApplicationRole_Result objectItem in usergroup)
{
sample += "<li id= "+objectItem.group_id+ " class='ui-state-highlight'>";
sample += objectItem.group_name;
sample+="</li>";
}
return sample;
}
How to avoid duplicate value in this... Please help me out..
Thanks in advance..
Hi change your javascript as follows:
<script>
function ShowSortable() {
$('#sortable1').show();
var postJSONData = JSON.stringify({ ApplicationId: $('#applnhdnname').val(), RoleName: $('#RoleName').val() });
$.ajax({
type: 'POST',
data: postJSONData,
url: 'UserManagementService.svc/GetUserGroupsForApplicationRole',
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function success(response) {
for(var i=0; i<response.d.length;i++)
{
var myOption = $("<option value= " + response.d[i] + "> " + response.d[i] + " </option>");
if ($("#sortable2").length == 0) {
$("#sortable2").append(myOption);
}
$("#sortable2> option").each(function() {
if (response.d[i] != this.value) {
$("#sortable2").append(myOption);
}
});
}
$('#sortable2').show();
},
error: SessionExpiryHandler
});
}
</script>

MVC3 JSON Ajax error

I am trying to make an ajax sending data in JSON from a partial view. I get a System.ArgumentException: Invalid JSON primitive: undefined.
When I evaluate the object in a browser data contains an int and two strings. Can anyone tell me what I am doing wrong?
Partial View
#model FTD.Models.FTDAccountExtended
#using (Html.BeginForm()) {
<fieldset>
<legend>Update Policy Number</legend>
#Html.HiddenFor(m => m.account.ftd_accountsid)
#Html.HiddenFor(m => m.OldPolicyNumber)
#Html.TextBoxFor(m => m.account.ftd_policyno)
<input type="button" value="update" id="update" />
</fieldset>
}
<script type="text/javascript">
$(document).ready(function () {
$("#update").click(function () {
var myUrl = '#Url.Content("~/")' + '/Maintenance/UpdatePolicyNumber';
var data = [{ 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()}];
$.ajax({
url: myUrl,
type: 'POST',
data: data,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.message);
},
error: function (errMsg) {
alert("Error", errMsg);
}
});
});
});
The controller method is
public ActionResult UpdatePolicyNumber(int ClientNumber, string OldPolicyNumber, string NewPolicyNumber)
{
var message = string.Format("UpdatePolicyNumber CN:{0} OP:{1} NP:{2}", ClientNumber, OldPolicyNumber, NewPolicyNumber);
if (_log.IsDebugEnabled)
_log.Debug(message);
if (!string.IsNullOrEmpty(NewPolicyNumber) && ClientNumber > 0)
{
_entities = new CloseFTD_Entities();
_entities.UpdatePolicyNumber(ClientNumber, OldPolicyNumber, NewPolicyNumber, User.Identity.Name);
}
return Json
(
new
{
message = message
},
JsonRequestBehavior.AllowGet
);
}
I would just try posting the the data as a java script object (as Marc mentioned above)
and remove the content type attribute.
success: function (data) {
alert(data.success);
},
shouldn't this be
success: function (data) {
alert(data.message);
},
Your problem is here
var data = [{ 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()}];
You are building an array - but your controller excepts the direct values, so just remove the [] brackets:
var data = { 'ClientNumber': parseInt($("#account_ftd_accountsid").val()), 'OldPolicyNumber': $("#OldPolicyNumber").val(), 'NewPolicyNumber': $("#account_ftd_policyno").val()};
That should work.

Categories

Resources