Passing response from ajax call to view in C# - c#

I am using ajax to call an action in the controller. The code is like this
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (selectedKitchen != '') {
console.log("selected item:" + $('#kitchen').val());
$.ajax({
type: "GET",
url: "/Home/GiveInsitutionsWithoutResponsibility",
data: "id=" + selectedKitchen,
dataType:'json',
success: function (result) {
result = JSON.parse(result);
console.log(result.length);
},
error: function (error) {
console.log("There was an error posting the data to the server: ");
console.log(error.responseText);
}
});
}
});
Now what I want is to use the result coming from the server to populate a drop down on the client side. How should I do it? Is there a way for it or my approach here is wrong?
My result object is like this
{
Id: "04409314-ea61-4367-8eee-2b5faf87e592"
Name: "Test Institution Two"
NextPatientId: 1
OwnerId: "1"
PartitionKey: "1"
RowKey: "04409314-ea61-4367-8eee-2b5faf87e592"
Timestamp: "/Date(1417180677580)/"
}
The controller function is like this
public ActionResult GiveInsitutionsWithoutResponsibility()
{
var kitchenId = Request["id"].ToString();
Kitchen k = Kitchen.Get(kitchenId);
IEnumerable <Institution> ins = k.GetInstitutions();
IEnumerable<Institution> allIns = Institution.GetAll();
List<Institution> result = new List<Institution>();
bool contain = true;
int index = 0;
if (ins.Count() > 0)
{
for (int i = 0; i < allIns.Count(); i++, contain = true)
{
for (int j = 0; j < ins.Count(); j++)
{
if (allIns.ElementAt(i).Id == ins.ElementAt(j).Id)
{
contain = true;
break;
}
else
{
index = j;
contain = false;
}
}
if (!contain)
{
result.Add(allIns.ElementAt(index));
}
}
}
else
{
for (int i = 0; i < allIns.Count(); i++)
{
result.Add(allIns.ElementAt(index));
}
}
string response = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(result);
return Json(response, JsonRequestBehavior.AllowGet);
}

First your action method can be simplified to
public ActionResult GiveInsitutionsWithoutResponsibility(int ID)
{
Kitchen k = Kitchen.Get(ID);
var data = Institution.GetAll().Except(k.GetInstitutions(), new InstitutionComparer()).Select(i => new
{
ID = i.ID,
Name = r.Name
});
return Json(data, JsonRequestBehavior.AllowGet);
}
Note the Kitchen.ID is passed in the method parameter. The Linq query is used to select all Institution's then exclude any Institution's that already exist in the Kitchen, then creates a collections of anonymous object so unnecessary data is not sent to the client. The Json() method returns the data in the correct JSON format (calling JavaScriptSerializer().Serialize() is not required).
In order for .Except() to work with complex objects, you need a comparer
public class InstitutionComparer : IEqualityComparer<Institution>
{
public bool Equals(Institution x, Institution y)
{
if (Object.ReferenceEquals(x, y))
{
return true;
}
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
{
return false;
}
return x.ID == y.ID;
}
public int GetHashCode(Institution institution)
{
if (Object.ReferenceEquals(institution, null))
{
return 0;
}
return institution.ID.GetHashCode();
}
}
Next change the ajax method to
$('#kitchen').change(function () {
var selectedKitchen = $('#kitchen').val();
if (!selectedKitchen) {
return;
}
$.ajax({
type: "GET",
url: '#Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', // don't hard code urls
data: { id: selectedKitchen }, // pass selectedKitchen to the id parameter
dataType:'json',
success: function (result) {
var select = $('YourDropDownSelector').empty().append($('<option></option>').val('').text('--Please select--'));
$.each(result, function(index, item) {
select.append($('<option></option>').val(item.ID).text(item.Name));
});
},
error: function (error) {
}
});
});
or you could use the short cut
$.getJSON('#Url.Action("GiveInsitutionsWithoutResponsibility", "Home")', { id: selectedKitchen }, function(result) {
$.each(result, .... // as above
});

Depending on the object from your controller, you could loop through your results data and .append this to your drop down list.
success: function (result) {
$.each(result, function(index, manager) {
$('select#yourId').append(
'<option value="' + result.Id + '">'
+ result.Name +
'</option>');
});
}

Your approach is fine, you will have to format the result to be added to combo box. For example, support on a page I have country and states combo box. Based on selected country, I need to populate state, so I will write following code:
$("#billingContactCountry").change(function (e) {
e.preventDefault();
var countryId = $("#billingContactCountry").val();
getStatesByCountry(countryId, "", "#billingContactState", "#billingContactZip");
});
function getStatesByCountry(countryId, stateId, stateCombobox, zipTextBox) {
$.ajax({
url: "#Url.Action("GetStatesByCountry", "Admin")",
data: { countryId: countryId },
dataType: "json",
type: "GET",
error: function (xhr, status) {
//debugger;
var items = "<option value=\"\">-Select State-</option>";
$(stateCombobox).html(items);
var zipMessage = validateZip(countryId, $(zipTextBox).val());
if (zipMessage != "The ZIP Code field is required.") {
$(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
}
$("div.overlay").hide();
},
success: function (data) {
//debugger;
var items = "<option value=\"\">-Select State-</option>";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
});
$(stateCombobox).html(items);
if (stateId != "") {
$('#billingContactState').val(stateId);
}
var zipMessage = validateZip(countryId, $(zipTextBox).val());
if (zipMessage != "The ZIP Code field is required.") {
$(zipTextBox).parent().find("span.field-validation-error").text(zipMessage);
}
$("div.overlay").hide();
}
});
}
So basically interesting code is,
var items = "<option value=\"\">-Select State-</option>";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Id + "\">" + item.Name + "</option>";
});
$(stateCombobox).html(items);
We are operating on each element returned from server to create option item for combo box.
As an aside, you should use #Url.Action as shown in example above.

Related

Parameter in my C# controller read as null from the AJAX call

I'm trying to take input from Users through a checkbox and store it in a table in my SQL DB, I've created all the link properly and my post AJAX call works well because I was able to receive information in my DB. The problem is the parameter received in my controller is receiving a null value which is storing a null value in my table, I know that my checkbox is pulling the right information because im printing it before hand but I feel like my AJAX setup may not be stringifying it properly.
$("#submitButton").click(function() {
var results = {};
$questions = $('#optionData');
for (i = 1; i < 6; i++) {
if ($questions.find('#option' + i).prop('checked')) {
results['option' + i] = $questions.find('#option' + i).val();
}
newResult = JSON.stringify(results)
};
console.log(newResult);
$.ajax({
url: "/Home/SaveData",
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: (newResult),
success: function(data) {
if (data == null) {
alert("Something went wrong");
}
},
failure: function(data) {
alert(data.dataText);
},
error: function(data) {
alert(data.dataText);
}
});
});
[HttpPost]
public ActionResult SaveData(string Options)
{
dataInsertion dataInsertion = new dataInsertion
{
// questionID = object.QuestionId,
options = Options,
// },
// companyID = object.companyID
};
try
{
if (ModelState.IsValid)
{
DB.dataInsertions.Add(dataInsertion);
DB.SaveChanges();
// RedirectToAction("Home");
}
}
catch (Exception e)
{
Console.WriteLine("error" + e);
}
return Json(new { sucess = "true" });
}

Ajax Request return : data Udefined After Success

I am trying to do some Get_Data from dataBase Using asynchronous ajax request and WebMethod
Everything works fine , but when i want the returned value from my web method value , i got undefined value
I Know That this question is asked before
I have tried almost all advices to achieve my wanted goal , but unfortunately nothing happened .
Create Instance Outside the function than set it to the return value.
Set The dataType:"Json"
Create an instance inside the function and set it to empty string
var ReturnValue="";
Let Json object stringify my returned value
and many other steps
So please do not mark my question as duplicated value
Here is my code below :
//Javascript and Jquery Codes
$(document).ready(function() {
$("#PValidateLogin").hide();
});
function killSpaces(element) {
var characters = element.toString();
var resultText = "";
for (var i = 0; i < characters.length; i++) {
if (!(characters[i] == " ")) {
resultText += characters[i];
}
}
return resultText;
}
$("#<%=btnLogin.ClientID%>").click(function() {
var MyWantedhref;
var Result = ValidateMyLogin();
if (typeof Result === "undefined") {
alert("Something wrong with codes");
} else if (Result == "false" || killSpaces(Result).length == 0) {
alert("wrong user ");
} else {
MyWantedhref = "/Frm_Manager/frm_MenuCategory.aspx";
location.replace(MyWantedhref);
}
});
function ValidateMyLogin() {
var ReturValue;
var UserName = $("#<%=txtUserName.ClientID%>").val();
var Password = $("#<%=txtUserPassword.ClientID%>").val();
if (killSpaces(Password).length >= 4 && killSpaces(UserName).length >= 4) {
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
url: "frm_ValidateLogin.aspx/ValidateLogin",
data: "{'UserName':'" + UserName + "','Password':'" + Password + "'}",
success: function(data) {
ReturValue = data.d;
},
error: function(err) {
ReturValue = err.d;
}
});
}
return ReturValue;
}
And Here are the C# Code
<code>
private static OwnerAccountBO _OwnerAccountBO;
public static OwnerAccountBO OwnerAccountBO { get { return new OwnerAccountBO(); } set { _OwnerAccountBO = value; } }
[WebMethod(EnableSession = true)]
public static string ValidateLogin(string UserName, string Password)
{
string CharResult = "";
object[] UserParameters = { UserName, Password };
int Result = OwnerAccountBO.validateLogin(UserParameters);
if (Result > 0)
{
HttpContext.Current.Session["OwnerAccountID"] = Result;
CharResult += Convert.ToString(Result);
}
else
{
CharResult += "false";
}
return CharResult;
}
</code>
Please Any Help would be thankful .
And of course i want a proper explication for the wrong action or flow that i am doing to have such error
You returned a string value from the method
string CharResult = "";
object[] UserParameters = { UserName, Password };
int Result = OwnerAccountBO.validateLogin(UserParameters);
if (Result > 0)
{
HttpContext.Current.Session["OwnerAccountID"] = Result;
CharResult += Convert.ToString(Result);
}
else
{
CharResult += "false";
}
return CharResult;
so in you ajax it must be received like this
$.ajax({
success: function (data)
{
ReturValue = data; //fixed it with this
}
});
Not
$.ajax({ success: function (data)
{
ReturValue = data.d; //issue here
},
error: function (err)
{
ReturValue = err.d;
}
});

How can i get remote call on bootstrap twitter typeahead to work, by calling asp.net web method

I am trying to load my typeahead.js by using bloohound's remote function where i can call my Web Method. I have seen similar threads where a querystring is being used :
Integrating Typeahead.js with ASP.Net Webmethod
Typeahead.js and Bloodhound.js integration with C# WebForms WebMethod
http://yassershaikh.com/using-twitter-typeahead-js-with-asp-net-mvc-web-api/
And many more....
However, i cannot find an example where ajax is used to call the webmethod from typeahead.js.
So this is what i have currently and it works:
WebMethod
[WebMethod]
public static string GetEmployeeTypeahead()
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = 100000000;
string json;
using (var rep = new RBZPOS_CSHARPEntities())
{
var result = rep.Employees
.Where(x => x.EMPLOYEESTATE == 1)
.Select(x => new {
x.EMPLOYEEID,
x.FULLNAME,
x.MANNO,
x.NRC
}).ToList();
json = jss.Serialize(result);
}
return json;
}
The Client
function LoadEmployeeJSON() {
$.ajax({
type: "POST",
url: "/WebMethods/Test.aspx/GetEmployeeTypeahead",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
empList = $.parseJSON(msg.d); //otherwise does not work
LoadEmployeeTypeahead();
},
error: function (msg) {
alert("error:" + JSON.stringify(msg));
}
});
}
function LoadEmployeeTypeahead() {
var empData = empList;
var fullname = new Bloodhound({
datumTokenizer: function (d) {
return Bloodhound.tokenizers.whitespace(d.FULLNAME)
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: empData,
limit: 10
});
fullname.initialize();
// Make the code less verbose by creating variables for the following
var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
// Initialise typeahead for the employee name
fullnameTypeahead.typeahead({
highlight: true
}, {
name: 'FULLNAME',
displayKey: 'FULLNAME',
source: fullname.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
}
}
});
var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
/* See comment in previous method */
$('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
$('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
$('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
$('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
};
// Associate the typeahead:selected event with the bespoke handler
fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
}
function clearAndReInitilize() {
$('.typeahead').typeahead('destroy');
$('.typeahead').val('');
}
So as you can see i am making a local call instead of remote.
How can i get the remote function to call my webthod and fill the typeahead without using any querystrings
Okay finally got it to work via an ashx generic handler. So instead of using a web method i used the following ashx handler:
public class Employess : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.MaxJsonLength = Int32.MaxValue;
string json;
string prefixText = context.Request.QueryString["query"];
using (var rep = new RBZPOS_CSHARPEntities())
{
var result = rep.Employees
.Where(x => x.EMPLOYEESTATE == 1 && x.FULLNAME.Contains(prefixText.ToUpper()))
.Select(x => new
{
x.EMPLOYEEID,
x.FULLNAME,
x.MANNO,
x.NRC
}).ToArray();
json = jss.Serialize(result);
}
context.Response.ContentType = "text/javascript";
context.Response.Write(json);
}
public bool IsReusable
{
get
{
return false;
}
}
}
Below is the jquery and the ajax call to the ashx handler
$(document).ready(function () {
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
LoadEmployeeTypeahead();
// LoadEmployeeJSON();
});
function LoadEmployeeTypeahead() {
//var empData = empList;
var fullname = new Bloodhound({
remote: {
url: '/Employess.ashx?query=%QUERY',
wildcard: '%QUERY'
},
datumTokenizer: function (d) {
//var employees = $.parseJSON(msg.d);
return Bloodhound.tokenizers.whitespace(d.FULLNAME)
},
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10
});
fullname.initialize();
// Make the code less verbose by creating variables for the following
var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
// Initialise typeahead for the employee name
fullnameTypeahead.typeahead({
highlight: true
}, {
name: 'FULLNAME',
displayKey: 'FULLNAME',
source: fullname.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'No match',
'</div>'
].join('\n'),
suggestion: function (data) {
return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.MANNO + "</em></span><span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
}
}
});
var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
/* See comment in previous method */
$('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
$('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
$('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
$('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
};
// Associate the typeahead:selected event with the bespoke handler
fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
}

Ko ObservableArray object not updating Via WebAPI

I have an observable array Object that which is generated like this:
self.SelectedVariable = ko.observableArray();
self.VarUpdate = function (data) {
$.getJSON("/api/Variable/" + ko.toJS(data.VarID), ko.toJS(data.VarID), function (Result) {
for (var i = 0; i < Result.length; i++) {
element = Result[i];
self.SelectedVariable({ VariableID: ko.observable(element.VariableID), VariableDateLastUpdated: ko.observable(element.VariableDateLastUpdated), VariableName: ko.observable(element.VariableName), VariableDescription: ko.observable(element.VariableDescription), VariableValue: ko.observable(element.VariableValue), VariableType: ko.observable(element.VariableType) });
};
});
When I try to pass the SelectedVariable object to my WebAPI method using this AJAX call
$.ajax({
url: "/api/Variable?Del=0",
data: { vardata: ko.toJS(self.SelectedVariable) },
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
, all the related object shows null on all the fields.
I have tried almost every combination to get the SelectedVariable Object to parse correctly to my WebAPI method:
data: { vardata: ko.toJS(self.SelectedVariable) },
data: { vardata: ko.toJSON(self.SelectedVariable) },
data: { vardata: JSON.Stringify(self.SelectedVariable) },
data: { vardata: self.SelectedVariable },
and have tried to manually decrypt JSON object on WebAPI side using:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata);
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
And It is still null value.
Any Advice would be greatly appreciated!
UPDATE
Changed my WebAPI method to reflect as follows:
public void Put([FromUri] int Del, IEnumerable<Variables> vardata)
{
var Item = (from c in TMIRE.Variables
where c.VariableID == vardata.Select(x => x.VariableID).First()
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
vardata.Select(a => Item.VariableName = a.VariableName);
vardata.Select(b => Item.VariableDescription = b.VariableDescription);
vardata.Select(c => Item.VariableValue = c.VariableValue);
vardata.Select(d => Item.VariableType = d.VariableType);
}
and now the vardata object gets the value but all objects within are null
My Ajax method looks like this:
alert(ko.toJSON(self.SelectedVariable));
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable()),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
The alert gives me this response
The Variables Class
public class Variables
{
public int VariableID { get; set; }
public DateTime VarialbeDateLastUpdated { get; set; }
public string VariableName { get; set; }
public string VariableDescription { get; set; }
public string VariableValue { get; set; }
public string VariableType { get; set; }
}
Working Code
By using this Ajax call
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
and then using Newtonsoft to deserialize the object on WebAPI using this method:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata.Substring(1, vardata.Length-2));
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
}
else
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableActive = false;
}
TMIRE.SaveChanges();
}
I Got it to work
Try this...
public void Put([FromUri] int Del, IEnumerable<Variables> vardate){}
Since you're building a collection on the client self.SelectedVariable = ko.observableArray();, you will need the API to receive an IEnumerable.
In the Ajax call, I think it would be best to use:
data: { vardata: ko.toJSON(self.SelectedVariable) }
as this will give you a JSON representation of the collection.
Also, on the KO side, shouldn't you be pushing elements into the collection? self.SelectedVariable.push({...}); or you will end up with only the final result.
Change assignment to this:
self.SelectedVariable = ko.observableArray();
self.VarUpdate = function (data) {
$.getJSON("/api/Variable/" + ko.toJS(data.VarID), ko.toJS(data.VarID), function (Result) {
var selection = self.SelectedVariable;
for (var i = 0; i < Result.length; i++) {
var element = Result[i];
selection.push(element);
};
});
Then, Change the ajax method to convert to json:
$.ajax({
url: "/api/Variable?Del=0",
content-type: "application/x-www-form-urlencoded",
data: "=" + JSON.stringify(ko.toJSON(self.SelectedVariable)),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
Also try removing [FromBody].
public void Put([FromUri] int Del, IEnumerable<Variables> vardata)
{
...
}
It looks like making the serialized objects in vardata as ko.observable objects is confusing mvc serialization for the parameters.
different data assignments to attempt:
data: "=" + JSON.stringify(ko.toJSON(self.SelectedVariable))
data: "=" + JSON.stringify(self.SelectedVariable())
data: "=" + self.SelectedVariable()
data: "=" + $.parseJSON(ko.toJSON(self.SelectedVariable))
What you're passing self.SelectedVariable isn't an array. Should you not be calling it just an observable? Otherwise, you need to be adding your results with self.SelectedVariable.push(resultObject).
By using this Ajax call
$.ajax({
url: "/api/Variable?Del=0",
contenttype: "application/x-www-form-urlencoded",
data: "=" + ko.toJSON(self.SelectedVariable),
type: "PUT",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
and then using Newtonsoft to deserialize the object on WebAPI using this method:
public void Put([FromUri] int Del, [FromBody]string vardata)
{
Variables vari = JsonConvert.DeserializeObject<Variables>(vardata.Substring(1, vardata.Length-2));
var Item = (from c in TMIRE.Variables
where c.VariableID == vari.VariableID
select c).First();
if (Del == 0)
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableName = vari.VariableName;
Item.VariableDescription = vari.VariableDescription;
Item.VariableValue = vari.VariableValue;
Item.VariableType = vari.VariableType;
}
else
{
Item.VariableDateUpdated = DateTime.Now;
Item.VariableActive = false;
}
TMIRE.SaveChanges();
}

JQuery.Ajax and MVC4

I have a need to call a method on my controller to return a complex type using the JQuery.Ajax method.
function CallMethodTest(Id) {
//alert(Id);
$.ajax({
type: 'POST',
url: '/MyController/MyMethod',
dataType: "json",
contentType: "application/json; charset=utf-8",
//data: "{'Id': '" + Id + "'}",
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
[System.Web.Services.WebMethod]
public string MyMethod()
{
return "ABC"; // Gives me the error on the first alert of "200" and the second alert "Syntax Error: Invalid Character"
return "1"; // Works fine
}
As the code explains, if I return an integer (as a string) the return works and I alert "1", however, If I try and return any alpha characters I get the alerts shown in the comments of MyMethod.
From your code, it looks as though you are returning the value from your Controller url: "/MyController/MyMethod"
If you are returning the value from your controller, then get rid of the [System.Web.Services.WebMethod] code and replace it with this ActionResult
[HttpPost]
public ActionResult MyMethod(){
return Json("ABC");
}
Also, if you are ever going to call a method in your controller via GET then use
public ActionResult MyMethod(){
return Json("ABC", JsonRequestBehavior.AllowGet);
}
In View You use the following code,
function ItemCapacity() {
$.ajax({
type: "POST",
url: '#Url.Action("ItemCapacityList", "SalesDept")',
data: { 'itemCategoryId': itemCategoryIds },
dataType: 'json',
cache: false,
success: function (data) {
var capacityCounter = 0;
var capacitySelected = "";
for (var i = 0; i < rowsCount; i++) {
var tr = $("#gvSpareSetItemsDetails tbody tr:eq(" + i + ")");
var categoryId = $(tr).find('td:eq(5)').text();
var isSelectOrNot = $(tr).find('td:eq(1)').find('select');
if (isSelectOrNot.is('select')) {
$.map(data, function (item) {
if (categoryId == item.ItemCategoryID) {
isSelectOrNot.get(0).options[isSelectOrNot.get(0).options.length] = new Option(item.CapacityDescription, item.ItemCapacityID);
capacityCounter = capacityCounter + 1;
capacitySelected = item.ItemCapacityID;
}
});
if (capacityCounter == 1) {
isSelectOrNot.val(capacitySelected);
}
capacityCounter = 0;
capacitySelected = "";
}
}
},
error: function () { alert("Connection Failed. Please Try Again"); }
});
}
}
In the Controller Use the following Code,
public JsonResult ItemCapacityList(string itemCategoryId)
{
List<ItemCapacity> lsItemCapacity = new List<ItemCapacity>();
string[] itemCategory = itemCategoryId.Split('#');
int itemCategoryLength = itemCategory.Length, rowCount = 0;
string itemCategoryIds = string.Empty;
for (rowCount = 0; rowCount < itemCategoryLength; rowCount++)
{
itemCategoryIds += "'" + itemCategory[rowCount].Trim() + "',";
}
itemCategoryIds = itemCategoryIds.Remove(itemCategoryIds.Length - 1);
lsItemCapacity = salesDal.ReadItemCapacityByCategoryId(itemCategoryIds);
return new JsonResult { Data = lsItemCapacity };
}

Categories

Resources