Nested models don't bind - ajax

I want to pass a JSON data structure to an MVC (3) Controller, have the JSON object be translated into a C# object, with all properties bound. One of the properties is a simple Type. That's basic model binding, right?
Here are my models:
public class Person
{
public string Name { get; set; }
public JobTitle JobTitle { get; set; }
}
public class JobTitle
{
public string Title { get; set; }
public bool IsSenior { get; set; }
}
Here is my Index.cshtml page (which makes an AJAX request, passing in a JSON object which matches the strcture of the "Person" class):
<div id="myDiv" style="border:1px solid #F00"></div>
<script type="text/javascript">
var person = {
Name: "Bob Smith",
JobTitle: {
Title: "Developer",
IsSenior: true
}
};
$.ajax({
url: "#Url.Action("ShowPerson", "Home")",
data: $.param(person),
success: function (response){
$("#myDiv").html(response);
},
error: function (xhr) {
$("#myDiv").html("<h1>FAIL</h1><p>" + xhr.statusText + "</p>");
}
});
</script>
And my HomeController looks like this:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ShowPerson(Person person)
{
return View(person);
}
}
Ignore the "ShowPerson.cshtml" file for now because the problem occurs before that is ever needed.
In the HomeController.ShowPerson action, the "person.Name" property is correctly bound and the "person.JobTitle" object (containing "Title" and "IsSenior" properties) is instantiated but still has the default values of "Title = null" and "IsSenior = false".
I'm sure I have done nested model binding without problem in the past. What am I missing? Can anybody shed any light on why model binding only seems to work one level deep?
I've searched SO, and it seems everybody else is having binding problems when sending data from forms, so maybe I'm missing something in my $.ajax() request?

ok, there are couple of changes you need to do,
Set dataType as json
Set the contentType as application/json; charset=utf-8.
Use JSON.stringify()
below is the modified code. (tested)
var person = {
Name: "Bob Smith",
JobTitle: {
Title: "Developer",
IsSenior: true
}
};
var jsonData = JSON.stringify(person);
$.ajax({
url: "#Url.Action("ShowPerson", "Home")",
data: jsonData,
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (response){
$("#myDiv").html(response);
},
error: function (xhr) {
$("#myDiv").html("<h1>FAIL</h1><p>" + xhr.statusText + "</p>");
}
});

Add the content type to the ajax
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
data: $.toJSON(person);

Related

MVC Controller post json does not work

I have the this code to post json to a controller.
The problem is that the credentials object does not get populated with the posted values.
How do I change this code so that it works?
I see in Fiddler that the request is being posted correctly.
[HttpPost]
public JsonResult Authenticate(CredentialsModel credentials)
{
return Json(credentials);
}
[DataContract]
public class CredentialsModel
{
[DataMember(Name = "user")]
public string User;
[DataMember(Name = "pass")]
public string Pass;
}
$.ajax({
type: "POST",
url: "/login/authenticate",
cache: false,
contentType: "application/json; charset=utf-8",
data: '{"user":' + JSON.stringify($('#username').val()) + ',"uass":' + JSON.stringify($('#userpass').val()) + '}',
dataType: "json",
timeout: 100,
success: function (msg) {
},
complete: function (jqXHR, status) {
if (status == 'success' || status == 'notmodified') {
var obj = jQuery.parseJSON(jqXHR.responseText);
}
},
error: function (req, status, error) {
}
});
The default MVC model binder only works with properties. Your CredentialsModel is using fields. Try changing them to properties. You can also remove the annotations.
public class CredentialsModel
{
public string User { get; set; }
public string Pass { get; set; }
}
Also, as pointed out by Sahib, you can create a Javascript Object and then stringify it, rather than stringifying each one. Although that doesn't appear to be the problem in this case.
data: JSON.stringify({
User: $('#username').val(),
Pass: $('#userpass').val()
})
Try chaning your data like this :
$.ajax({
.................
//notice the 'U' and 'P'. I have changed those to exactly match with your model field.
data: JSON.stringify({User: $('#username').val(),Pass: $('#userpass').val()}),
.................
});

JSON and ASP.Net MVC Controller is not binding the properties of the list of objects

I am making an AJAX call with jQuery:
var topic = new Array();
$('.container-topico').each(function (i) {
topic.push(
{
"TopicsModel":
{
begins: $(this).find('.HoursStart').val(),
ends: $(this).find('.HoursEnd').val(),
texts: $(this).find('.input-topic').val()
}
}
);
});
var data = JSON.stringify({
videoId: '<%=Url.RequestContext.RouteData.Values["id"]%>',
topics: topic
});
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '<%= Url.Action("SubmitTopics") %>',
traditional: true,
data:
data
,
beforeSend: function (XMLHttpRequest) {
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
},
success: function (data, textStatus, XMLHttpRequest) {
$(data).each(function () {
});
}
});
It is sending the JSON in the format (e.g):
{"videoId":"1","topics":
[{"TopicsModel": {"begins":"00:00:33","ends":"00:01:00","texts":"1. Primeiro tema"}},
{"TopicsModel": {"begins":"00:01:00","ends":"00:01:33","texts":"2. Segundo tema"}},
{"TopicsModel": {"begins":"00:01:33","ends":"00:02:00","texts":"3. Terceiro tema"}},
{"TopicsModel": {"begins":"00:02:00","ends":"00:00:21","texts":"dasdasdsa ada as das s"}},
{"TopicsModel": {"begins":"0","ends":"0","texts":""}}]}
And on the server side it has the Model:
public class TopicsModel
{
public string begins;
public string ends;
public string texts;
}
and the Controller:
public ActionResult SubmitTopics(int videoId, List<TopicsModel> topics)
What happen is:
It have the correct number of objects, but is not binding the properties of each element, as you can see bellow:
Why is it not binding to the properties ?
The binding can't find the TopicsModel property in your TopicsModel object, so it can't bind the value.
Try this instead :
{"videoId":"1","topics":
[{"begins":"00:00:33","ends":"00:01:00","texts":"1. Primeiro tema"},
{"begins":"00:01:00","ends":"00:01:33","texts":"2. Segundo tema"},
{"begins":"00:01:33","ends":"00:02:00","texts":"3. Terceiro tema"},
{"begins":"00:02:00","ends":"00:00:21","texts":"dasdasdsa ada as das s"},
{"begins":"0","ends":"0","texts":""}]}
The binding should then resume normally.
You also have to change your model this way :
public class TopicsModel
{
public string begins { get; set; }
public string ends { get; set; }
public string texts { get; set; }
}
Try re-naming List<TopicsModel> topics in the controller parameter list to List<TopicsModel> model

Pass List from view to controller

i am trying to pass List from view to controller but i am getting null value. code is written as follows :
model class :
public class testModel
{
public int ID { get; set; }
public string Name { get; set; }
public List<myModel> ParameterList {get;set;}
}
jquery and ajax code to post data to controller :
var myModel = {
"Name":"test",
"Description":"desc"
};
var Object = {
Name: $("#Name").val(),
ParameterList : myModel
};
$.ajax({
url: '/controller/action',
type: 'POST',
data: JSON.stringify(Object),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) { }
else { }
}
});
i am getting value for Name property but not for ParameterList.
What is wrong here ? am i missing anything ?
Please help me out.
Thanks
Edit : Controller Code from comments,
public JsonResult Save(Object Obj)
{
// logic for managing model and db save
}
You said,
I am getting value for Name property but not for ParameterList.
Which makes me wonder what is the structure of myModel, as you have declared ParameterList as a list of myModel type : List<myModel> ParameterList
Also I would recommend you to log JSON.stringify(Object) to console and check the Json value you are actually posting to the controller.
Here is what I found you must be posting back
{"Name":"yasser","ParameterList":{"Name":"test","Description":"desc"}}
Also read these articles :
How can I pass complex json object view to controller in ASP.net MVC
Pass JSON object from Javascript code to MVC controller
Try this:
var myModel = [{
"Name":"test",
"Description":"desc"
}];
var Object = {
Name: $("#Name").val(),
ParameterList : myModel
};
$.ajax({
url: '/controller/action',
type: 'POST',
data: Object,
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) { }
else { }
}
});
Just try like this..Hope this would help!!
script:
var emp = [{ 'empid': 1, 'name': 'sasi' },{ 'empid': 2, 'name': 'sathish'}];
emp = JSON.stringify(emp)
$.post("/Home/getemplist/", { 'emp': emp })
Controller:
Here i just changed the parameter to string type. using JavaScriptSerializer you can able to convert this string data to your class list objects.. you can understand it better if u see my code below:
public void getemplist(string emp)
{
List<Emp> personData;
JavaScriptSerializer jss = new JavaScriptSerializer();
personData = jss.Deserialize<List<Emp>>(emp);
// DO YOUR OPERATION ON LIST OBJECT
}

json ajax complex type pass to MVC2 action

I know this has been asked before in a similar form, but I have hit a bit of problem here....
I have this classic problem of trying to pass a json complex type to MVC2.
The problem (refer to the code below): I can pass the value "subincidentID" to the controller but the values "CodeType", "MOCode" and "SubCode" are all NULL.
I HAVE installed the MVC2 future and registered "Microsoft.Web.MVC" in global.asax.cs and declare the JsonValueProviderFactory.
The JQuery bit:
$('#btnDone').click(function() {
var entity = {};
var dbCode = new Array();
dbCode[0] = { CodeType: "1", MoCode: "13", SubCode: "12" };
entity = { subincidentID: "1", codeData: dbCode };
$.ajax({
type: 'POST',
data: entity,
dataType: 'json',
async: false,
url: "/controller/SaveMOData",
success: function(result) {
alert('success!');
}
}); //end of post
}); //end of btnDone click function
Controller in MVC:
[HttpPost]
public JsonResult SaveMOData(MOSubMitModel mo)
{
if (ModelState.IsValid)
{
}
return Json(new { success = "true" });
}
Model class in MVC (2):
public class MOSubMitModel
{
public int subIncidentID { get; set; }
public List<dbCode> codeData { get; set; }
}
public class dbCode
{
public string CodeType { get; set; }
public string subCode { get; set; }
public string MoCode { get; set; }
}
Have I missed something here?
Do I have to declare any namespace on the controller page?
I am sure it is a small problem but I have been scratching my head the whole day about it....:-(..
Thanks in advance.
W. Lam
I've heard of issues using the following syntax
$.ajax({
type: "POST",
data: {prop:"Value"},
....
}
Instead you need to stringify the object
$.ajax({
type: "POST",
data: JSON.stringify({prop:"Value"}),
....
}
After some more trial-and-error and readings I have finally figured it out myself (Refer to the previous posting for details of the other components):
$('#btnDone').click(function() {
:
:
$.ajax({
type: 'POST',
data: JSON.stringify(entity),
contentType: 'application/json',
async: false,
url: "/controller/SaveMOData",
success: function(result) {
alert('success!');
}
}); //end of post
}); //end of btnDone click function
The problem was me NOT to include "contentType" (I had tried to inclide json stringify before but it ALL returns NULL if I do not include contentType)...so...to summarise the requirements under MVC2:
Download MVC Future .....Unzip the MVC future zip file and copy Microsoft.web.mvc to your project, and reference it In your project's global.asax.cs file, include the "Microsoft.web.mvc" namespace, and then include the following line at the end of the function "Application_start"
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
Make the necessary changes in your jQuery as indicated above. It should be working (well it works for me!!)..Hope it helps anyone with the same problem.

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view

I'm a novice web programmer so please forgive me if some of my "jargon" is not correct.
I've got a project using ASP.NET using the MVC3 framework.
I am working on an admin view where the admin will modify a list of equipment. One of the functions is an "update" button that I want to use jquery to dynamically edit the entry on the webpage after sending a post to the MVC controller.
I presume this approach is "safe" in a single admin setting where there is minimal concern of the webpage getting out of sync with the database.
I've created a view that is strongly typed and was hoping to pass the model data to the MVC control using an AJAX post.
In the following post, I found something that is similar to what I am looking at doing:
JQuery Ajax and ASP.NET MVC3 causing null parameters
I will use the code sample from the above post.
Model:
public class AddressInfo
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
return Json(new { success = true });
}
}
script in View:
<script type="text/javascript">
var ai = {
Address1: "423 Judy Road",
Address2: "1001",
City: "New York",
State: "NY",
ZipCode: "10301",
Country: "USA"
};
$.ajax({
url: '/home/check',
type: 'POST',
data: JSON.stringify(ai),
contentType: 'application/json; charset=utf-8',
success: function (data.success) {
alert(data);
},
error: function () {
alert("error");
}
});
</script>
I have not had a chance to use the above yet. But I was wondering if this was the "best" method to pass the model data back to the MVC control using AJAX?
Should I be concerned about exposing the model information?
I found 3 ways to implement this:
C# class:
public class AddressInfo {
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
}
Action:
[HttpPost]
public ActionResult Check(AddressInfo addressInfo)
{
return Json(new { success = true });
}
JavaScript you can do it three ways:
1) Query String:
$.ajax({
url: '/en/Home/Check',
data: $('#form').serialize(),
type: 'POST',
});
Data here is a string.
"Address1=blah&Address2=blah&City=blah&State=blah&ZipCode=blah&Country=blah"
2) Object Array:
$.ajax({
url: '/en/Home/Check',
data: $('#form').serializeArray(),
type: 'POST',
});
Data here is an array of key/value pairs :
=[{name: 'Address1', value: 'blah'}, {name: 'Address2', value: 'blah'}, {name: 'City', value: 'blah'}, {name: 'State', value: 'blah'}, {name: 'ZipCode', value: 'blah'}, {name: 'Country', value: 'blah'}]
3) JSON:
$.ajax({
url: '/en/Home/Check',
data: JSON.stringify({ addressInfo:{//missing brackets
Address1: $('#address1').val(),
Address2: $('#address2').val(),
City: $('#City').val(),
State: $('#State').val(),
ZipCode: $('#ZipCode').val()}}),
type: 'POST',
contentType: 'application/json; charset=utf-8'
});
Data here is a serialized JSON string. Note that the name has to match the parameter name in the server!!
='{"addressInfo":{"Address1":"blah","Address2":"blah","City":"blah","State":"blah", "ZipCode", "blah", "Country", "blah"}}'
You can skip the var declaration and the stringify. Otherwise, that will work just fine.
$.ajax({
url: '/home/check',
type: 'POST',
data: {
Address1: "423 Judy Road",
Address2: "1001",
City: "New York",
State: "NY",
ZipCode: "10301",
Country: "USA"
},
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.success);
},
error: function () {
alert("error");
}
});
This is the way it worked for me:
$.post("/Controller/Action", $("#form").serialize(), function(json) {
// handle response
}, "json");
[HttpPost]
public ActionResult TV(MyModel id)
{
return Json(new { success = true });
}
what you have is fine - however to save some typing, you can simply use for your data
data: $('#formId').serialize()
see http://www.ryancoughlin.com/2009/05/04/how-to-use-jquery-to-serialize-ajax-forms/ for details, the syntax is pretty basic.
If using MVC 5 read this solution!
I know the question specifically called for MVC 3, but I stumbled upon this page with MVC 5 and wanted to post a solution for anyone else in my situation. I tried the above solutions, but they did not work for me, the Action Filter was never reached and I couldn't figure out why. I am using version 5 in my project and ended up with the following action filter:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
namespace SydHeller.Filters
{
public class ValidateJSONAntiForgeryHeader : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
string clientToken = filterContext.RequestContext.HttpContext.Request.Headers.Get(KEY_NAME);
if (clientToken == null)
{
throw new HttpAntiForgeryException(string.Format("Header does not contain {0}", KEY_NAME));
}
string serverToken = filterContext.HttpContext.Request.Cookies.Get(KEY_NAME).Value;
if (serverToken == null)
{
throw new HttpAntiForgeryException(string.Format("Cookies does not contain {0}", KEY_NAME));
}
System.Web.Helpers.AntiForgery.Validate(serverToken, clientToken);
}
private const string KEY_NAME = "__RequestVerificationToken";
}
}
-- Make note of the using System.Web.Mvc and using System.Web.Mvc.Filters, not the http libraries (I think that is one of the things that changed with MVC v5. --
Then just apply the filter [ValidateJSONAntiForgeryHeader] to your action (or controller) and it should get called correctly.
In my layout page right above </body> I have #AntiForgery.GetHtml();
Finally, in my Razor page, I do the ajax call as follows:
var formForgeryToken = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
type: "POST",
url: serviceURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: requestData,
headers: {
"__RequestVerificationToken": formForgeryToken
},
success: crimeDataSuccessFunc,
error: crimeDataErrorFunc
});

Resources