我正在 ASP.NET MVC4 上开发。我的代码中有两个提交 JSON 对象的 JSON 请求。其中一个工作正常,另一个由于某种原因传递了一个空值。有任何想法吗?
注意:在这两种情况下,请求实际上都到达了预期的控制器。只是第二个传递了一个 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);
}
更新:发票项目
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; }
}
我的凭据:
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 参数为空。