json response in ajax undefined - ajax

so here is my problem, I am returning a list of my model List from a controller through ajax. In response I am getting List but when i try to fill my datatable with this response it shows undefined everywhere
My View:
function GetData() {
pid = $(this).data('id');
var singleValues = $("#network").val();
var id = $(this).find(":selected").val();
var network = { "network": id };
$.ajax({
type: 'POST',
url: '/Home/GetData',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(network),
success: function (response) {
// console.log(response);
alert(response);
for (var i = 0; i < response.d.length; i++) {
$("#example").append("<tr><td>" + response.d[i].ACCOUNT_TYPE_ID + "</td><td>" + response.d[i].ACCOUNT_ISO_CODE + "</td><td>" + response.d[i].ACCOUNT_DESC + "</td></tr>");
debugger;
}
}
});
MY Controller:
[HttpPost]
public DbDataModel[] GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
DataTable db = GetDataSource(network);
foreach (DataRow row in db.Rows)
{
DbDataModel model = new DbDataModel();
model.Account_type_id = row["ACCOUNT_TYPE_ID"].ToString();
model.Account_iso_code = row["ACCOUNT_ISO_CODE"].ToString();
model.Account_desc = row["ACCOUNT_DESC"].ToString();
l.Add(model);
}
return l.ToArray();
}
My Model:
public class DbDataModel
{
public string Account_type_id { get; set; }
public string Account_iso_code { get; set; }
public string Account_desc { get; set; }
}

Change your method to return JSON
[HttpGet]
public JsonResult GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
.....
return Json(l, JsonRequestBehavior.AllowGet);
}
and in the script
...
$.ajax({
type: 'GET',
...

This is how i got it right.
function GetData() {
pid = $(this).data('id');
var singleValues = $("#network").val();
var id = $(this).find(":selected").val();
var network = { "network": id };
$.ajax({
type: 'POST',
url: '/Home/GetData',
dataType:"json",
traditional: true,
data: jQuery.param( network ),
success: function (response) {
debugger;
var oTable = $('#example').dataTable();//get the DataTable
oTable.fnClearTable();//clear the DataTable
for (var i = 0; i < response.length; i++) {
// $("#example").append("<tr><td>" + response[i].Account_type_id + "</td><td>" + response[i].Account_iso_code + "</td><td>" + response[i].Account_desc + "</td></tr>");
oTable.fnAddData([
response[i].Account_type_id,
response[i].Account_iso_code,
response[i].Account_desc
]);
}
}
});
};
[HttpPost]
public ActionResult GetData(string network)
{
List<DbDataModel> l = new List<DbDataModel>();
DataTable db = GetDataSource(network);
foreach (DataRow row in db.Rows)
{
DbDataModel model = new DbDataModel();
model.Account_type_id = row["ACCOUNT_TYPE_ID"].ToString();
model.Account_iso_code = row["ACCOUNT_ISO_CODE"].ToString();
model.Account_desc = row["ACCOUNT_DESC"].ToString();
l.Add(model);
}
return Json(l.ToArray(), JsonRequestBehavior.AllowGet);
}
Doing exactly what I wanted.

Related

ASP.net cascading dropdown list

trying to implement country state dropdown in mvc but couldn't..
conotroller :-
[HttpGet]
public ActionResult GetCities(int StateId)
{
Business.Services.City cityService = new Business.Services.City();
List<Business.Models.City> stateList = cityService.GetCityByStateId(StateId);
//var jsonSerialiser = new JavaScriptSerializer();
//var json = jsonSerialiser.Serialize(stateList);
return Json(new { stateList }, JsonRequestBehavior.AllowGet);
}
method:
public List<Models.City> GetCityByStateId(int StateId)
{
try
{
var list = new List<SelectListItem>();
Collection<DBParameters> parameters = new Collection<DBParameters>();
parameters.Add(new DBParameters() { Name = "StateId", DBType = DbType.Int32, Value = StateId });
var city = this.ExecuteProcedure<Models.City>("GetCityByState", parameters).ToList();
//if (city != null && city.Count > 0)
//{
// list = city.Select(x => new SelectListItem { Text = x.CityName, Value = x.StateId.ToString() }).ToList();
//}
return city;
}
catch (Exception ex)
{
throw;
}
}
change event:
$('.ddlstate').change(function () {
debugger;
$.ajax({
url: '#Url.Action("GetCities", "User")',
type: "GET",
data: { StateId: $(this).val() },
dataType: "json",
success: function (result) {
debugger;
//alert(result.stateList[0].CityId);
$.each(result.stateList, function () {
debugger;
$('.cityddl').append($("<option></option>").val(CityId).html(CityName));
});
},
error: function (result, status, jQxhr) {
alert("Error: " + result + "-" + status + "-" + jQxhr);
}
});
});
i get count of the citites in method and controller but when i run project and change state dropdown i got blank city dropdown. what is wrong?
It looks like you're missing a couple of things in the $.each() call.
You should pass the JSON result from the ajax call to the $.each
You also need to provide a parameter to the callback function so that the callback function has something to work with
It could look something like this:
$.each(result.stateList, function(index, city) {
$('.cityddl').append($("<option></option>").val(city.CityId).html(city.CityName));
});

NullReferenceException showing for ValidateAntiForgeryToken in MVC 5

I'm trying to save data using ajax in MVC 5. When I'm posting form data without #Html.AntiForgeryToken(), it's working nicely. But it's showing me Object reference not set to an instance of an object error for using #Html.AntiForgeryToken(). Here is my ajax code:
$.ajax({
type: "POST",
url: "/Employees/Create",
data: data,
async: false,
success: function (result) {
if (result == 1) {
window.location.href = '/Employees';
}
else {
$('#error-span').html('Error in insert.');
}
},
error: function () {
alert('Failed');
}
});
Here is my controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Address,JoinDate,DoB,Gender,BloodGroup,Email,LastName,FirstName,Mobile,UpdateDate,UpdatedBy,Status,EmployeeType,CreatedBy,CreateDate,DesignationId")] EmpDetail empDetail)
{
try
{
Regex rgx = new Regex("[^a-zA-Z0-9 - .]");
empDetail.FirstName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(rgx.Replace(empDetail.FirstName, "").ToLower()).Trim();
empDetail.LastName = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(rgx.Replace(empDetail.LastName, "").ToLower()).Trim();
empDetail.Email = empDetail.Email.ToLower().Trim();
empDetail.UpdateDate = DateTime.Now;
empDetail.CreatedBy = 234;
empDetail.CreateDate = DateTime.Now;
empDetail.UpdatedBy = 234;
empDetail.Status = 1;
if (ModelState.IsValid)
{
db.EmpDetails.Add(empDetail);
db.SaveChanges();
return Json(1);
}
else
{
return Json(2);
}
}
catch (Exception e)
{
return Json(e.Message);
}
}
This is happening because the data is being sent via JSON instead of HTML Form data. You should try to pass the token in the headers. For example:
View:
<script>
#functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$.ajax("api/values", {
type: "post",
contentType: "application/json",
data: { }, // JSON data goes here
dataType: "json",
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
</script>
Controller:
void ValidateRequestHeader(HttpRequestMessage request)
{
string cookieToken = "";
string formToken = "";
IEnumerable<string> tokenHeaders;
if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
{
string[] tokens = tokenHeaders.First().Split(':');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken);
}
Source: https://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-csrf-attacks

ajax call sending null value to controller

my model:
public class Hello
{
public List<string> name;
public List<string> phone;
public List<string> contact;
}
my controller code is
public ActionResult Home(Hello obj) // obj is coming out to be null
{
}
my script is
var names =[];
var phones =[];
var contacts = [];
// some code to fill the arrays
var obj = [{
name: names,
phone: phones,
contact: contacts,
}];
debugger;
$.ajax({
cache: false,
url: 'Home',
data: { obj:obj },
success: function (data) {
var response = JSON.parse(data);
window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
i can see in the debugger that data is stored in the arrays but when i am sending data to controller the obj is null can someone suggests where am i going wrong ?
You have object in code behind so do not pass array of Hello object.
And also use POST request because GET request have not message body.
Please use below
var obj = {
name: ['1', '2', '3'],
phone: ['234324', '34343243', '3434234234'],
contact: ['Test1', 'Test2', 'Test3']
};
debugger;
$.ajax({
type:'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'Home',
data:JSON.stringify({ obj: obj }),
success: function (data) {
var response = JSON.parse(data);
// window.location = 'Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
}
})
public class Hello
{
public List<string> name { get; set; }
public List<string> phone { get; set; }
public List<string> contact { get; set; }
}
Actually i solved the problem , i had to set
traditional:true,
in my ajax call

Data Inserted Successfully but ajax throwing error

Here is my ajax call function on button click
document.getElementById("btnSubmit").onclick = function ()
{
var txtImageName = $('#txtImageName').val();
var CategoryId = $('#cmbCategory').val();
var ImageURL = $('#txtImageURL').val();
var ImageSource = $('#textEditor').val();
var value = CKEDITOR.instances['textEditor'].getData()
alert
$.ajax({
url: "UrlwebService.asmx/InsertImage",
type: 'POST',
data: { ImageName: txtImageName, ImageUrl3x:ImageURL,ImageSource:value,CategoryId:parseInt(CategoryId) },
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function (Categories) {
// states is your JSON array
alert(Categories);
},
error: function (xhr, err) {
alert("I'm in terror");
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
};
I change content type to application/json it will also throwing me error
and here I'm calling this method.....
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void InsertImage(string ImageName, string ImageUrl3x, string ImageSource, int CategoryId)
{
var result = ImageRepo.InsertImage(ImageName,ImageUrl3x,ImageSource,CategoryId);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}

Passing complex objects to Action in asp.net MVC from jquery ajax

I have the following domain model defined:
public class myModel {
public string Prop1 {get;set;}
public string Prop2 {get;set;}
public List<myClass> ListofStuff {get;set;}
}
public myClass {
public string Id{get;set;}
public string Name{get;set;}
}
Then I have the controller action defined as follows:
[HttpPost]
public ActionResult Save(MyModel someModel )
{
//do the saving
}
I call the above action from my JS code using jquery ajax
var someModel = { Prop1: "somevalue1",
Prop2: "someothervalue",
ListofStuff: [{Id: "11", Name:"Johnny"}, {Id:"22", Name:"Jamie"}]
};
$.ajax({
contentType: 'application/json, charset=utf-8',
type: "POST",
url: "/myController/Save",
data: JSON.stringify({someModel: someModel}),
cache: false,
dataType: "json",
success: function () {
alert('success!');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
EDITED:
When I run the above code I get error handler gets executed. I tried to installed Firebug but my FF is version 8 and it couldn't install it. So I am not sure what the error is or how to see what it is for that matter.
What am I doing wrong?
I resolved the issue. MyClass needed to have a parameter-less constructor in order for the binding to work properly.
You can use following method for this purpose.
$.postifyData = function (value) {
var result = {};
var buildResult = function (object, prefix) {
for (var key in object) {
var postKey = isFinite(key)
? (prefix != "" ? prefix : "") + "[" + key + "]"
: (prefix != "" ? prefix + "." : "") + key;
switch (typeof (object[key])) {
case "number": case "string": case "boolean":
result[postKey] = object[key];
break;
case "object":
if (object[key] != null) {
if (object[key].toUTCString) result[postKey] = object[key].toUTCString().replace("UTC", "GMT");
else buildResult(object[key], postKey != "" ? postKey : key);
}
}
}
};
buildResult(value, "");
return result;
}
And after that you can pass model like.
var someModel = new Object();
someModel.Prop1 = "Pp1";
someModel.Prop2 = "PP2";
someModel.ListofStuff = new Array();
//Use for each loop to bind list like
for (var i = 0; i < 2; i++) {
var childObj = new Object();
childObj.Id = "123" + i;
childObj.Name = "Pankaj"
someModel.ListofStuff.push(childObj);
}
$.ajax({
type: "POST",
url: "/home/test",
data: $.postifyData(someModel),
cache: false,
dataType: "json",
success: function () {
alert('success!');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
i have checked it on my own and this is working fine.

Resources