我正在開發ASP.NET MVC4。 我的代碼中有兩個JSON請求提交了一個JSON對象。其中一個工作正常,另一個由於某種原因傳遞null。有任何想法嗎?類似的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*/);
}
});
});
工作控制器動作:接收一個空對象
$('#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);
}
});
});
控制器動作:
該傳遞NULL對象[Authorize(Roles = "edit,admin")]
public ActionResult AddToInvoice(InvoiceItem item)
{
return Json(item);
}
JavaScript的
[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);
}
UPDATE: 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
);
}
螢火蟲示出產品JSON對象,如所預期。也是「串化」的obj。 調試服務器端代碼顯示myCredential參數爲空。
哪裏是InvoiceItem和myCredential?也是你的路線定義。 – roryf
服務器端真的沒有收到任何東西嗎?什麼是螢火蟲?你的路線價值是什麼意思? – iappwebdev