我正在开发ASP.NET MVC4。 我的代码中有两个提交JSON对象的JSON请求。其中一个工作正常,另一个由于某种原因传递null。有什么想法吗?
注意:在两个实例中,请求实际上都到达了预期的控制器。只是第二个传递NULL,而不是我填充的对象。
正在运行的javascript:
$('#btnAdd').click(function () {
var item = {
Qty: $('#txtQty').val(),
Rate: $('#txtRate').val(),
VAT: $('#txtVat').val()
};
var obj = JSON.stringify(item);
$.ajax({
type: "POST",
url: "<%:Url.Action("AddToInvoice","Financials")%>",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: obj,
success: function (result) {
alert(result);
},
error: function (error) {
//do not add to cart
alert("There was an error while adding the item to the invoice."/* + error.responseText*/);
}
});
});
工作控制器动作:
[Authorize(Roles = "edit,admin")]
public ActionResult AddToInvoice(InvoiceItem item)
{
return Json(item);
}
传递NULL对象的javascript:
$('#btnApplyDiscount').click(function () {
var item = { user: $('#txtAdminUser').val(),password: $('#txtPassword').val(), isvalid: false };
var obj = JSON.stringify(item);
alert(obj);
$.ajax({
type: "POST",
url: "<%:Url.Action("IsUserAdmin","Financials")%>",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: obj,
success: function (result) {
if (result.isvalid)
{
//do stuff
}
else
{
alert("invalid credentials.");
}
},
error: function (error) {
//do not add to cart
alert("Error while verifying user." + error.responseText);
}
});
});
接收空对象的控制器操作:
[Authorize(Roles = "edit,admin")]
public ActionResult IsUserAdmin(myCredential user)
{
//validate our user
var usercount = (/*some LINQ happening here*/).Count();
user.isvalid = (usercount>0) ? true : false;
return Json(user);
}
更新: InvoiceItem
public partial class InvoiceItem
{
public Guid? id { get; set; }
public string InvCatCode { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public decimal VAT { get; set; }
public int Qty { get; set; }
public decimal Rate { get; set; }
public Nullable<decimal> DiscountAmount { get; set; }
public string DiscountComment { get; set; }
public Nullable<bool> IsNextFinYear { get; set; }
public Nullable<System.DateTime> ApplicableFinYear { get; set; }
}
myCredential:
public partial class myCredential
{
public string user { get; set; }
public string password { get; set; }
public bool? isvalid { get; set; }
}
路线值:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Firebug显示item是一个JSON对象,正如预期的那样。也是一个“字符串化”的对象。 调试服务器端代码显示myCredential参数为null。
答案 0 :(得分:6)
您不需要对对象进行字符串化,因为jQuery会为您执行此操作。我的猜测是,字符串化(如果这是一个单词)正在做的事情是混淆了ModelBinder。试试这个:
var obj = {
'user': $('#txtAdminUser').val(),
'password': $('#txtPassword').val(),
'isvalid': false
};
$.ajax({
data: obj,
// rest of your settings...
});
答案 1 :(得分:1)
试试这个...用于测试目的:
改变这个:
public ActionResult IsUserAdmin(myCredential user)
为此:
public ActionResult IsUserAdmin(myCredential item)