I am trying to send JSON to an Action method:
[HttpPost]
public virtual ActionResult KoUpdateAccount(CostCentreDTOX cc)
{
if (cc.NameCC == null)
{
return Json(new { message = "Im null" });
}
else
{
string s = cc.NameCC;
return Json(new { message = s });
}
}
Where CostCentreDTOX is defined as:
[Serializable]
public class CostCentreDTOX
{
public int CostCentreId { get; set; }
public int IdTr开发者_JAVA技巧ansactionType { get; set; }
public string NameCC { get; set; }
}
The Json is created by doing (I am using Knockoutjs):
var json = ko.toJSON(this.costCentres()[0]);
This produces the following string (which is what I want):
"{"CostCentreId":5,"IdTransactionType":2,"NameCC":"Impuestos"}"
The method that sends everything to the server is:
this.save = function() {
var json = ko.toJSON(this.costCentres()[0]);
api.postCud({
url: "/admin/Accounts/KoUpdateAccount/",
dataType: 'JSON',
data: json,
type: "post",
contentType: "application/json; charset=utf-8",
success: function(result) { alert(result.message) }
});
}
Where this.costCentre()[0] is an object defined as follows:
function costCentre(CostCentreId, IdTransactionType, NameCC) {
this.CostCentreId = ko.observable(CostCentreId);
this.IdTransactionType = ko.observable(IdTransactionType);
this.NameCC = ko.observable(NameCC);
}
However, the Action parameter cc just gets instantiated to its default values, as if the JsonValueProvider wasn't registered. But I am using ASP.NET MVC 3, so it should be there, right? Just there.
EDIT:
I have tried adding the following to the Global.asax file:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
But still, cc gets instantiated with default values.
any suggestions??
Is the api.postCud is that doing something exotic that could problems when it executes the post? Have you tried with $.ajax() instead just to see it that works?
As @Major Byte suspected, there was an issue with they way the ajax call was being made. This is done via a method, api.postCud, defined on an api.
The method is just a wrapper around $.ajax (see Eric Sowell's MvcConf2 video: Evolving Practices in Using jQuery and Ajax in ASP.NET MVC Applications). The problem being that it merges the options for the $.ajax call using $.extend() and I had included no provision for the dataType option.
So MVC was unaware that JSON was being posted, and therefore the model binding wasn't working.
This is what happens when I get 2 hours sleep...
精彩评论