类似的JSON请求,但一个发送null对象

Cap*_*chi 6 asp.net-mvc jquery json

我正在开发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*/);
                }
            });
        });
Run Code Online (Sandbox Code Playgroud)

工作控制器动作:

[Authorize(Roles = "edit,admin")]
public ActionResult AddToInvoice(InvoiceItem item)
{
    return Json(item);
}
Run Code Online (Sandbox Code Playgroud)

传递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);
                }
            });

        });
Run Code Online (Sandbox Code Playgroud)

接收空对象的控制器操作:

[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);
    }
Run Code Online (Sandbox Code Playgroud)

更新: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; }
}
Run Code Online (Sandbox Code Playgroud)

myCredential:

public partial class myCredential
{
    public string user     { get; set; }
    public string password { get; set; }
    public bool? isvalid    { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

路线值:

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
        );

    }
Run Code Online (Sandbox Code Playgroud)

Firebug显示item是一个JSON对象,正如预期的那样.也是一个"字符串化"的对象.调试服务器端代码显示myCredential参数为null.

Ror*_*san 6

您不需要对对象进行字符串化,因为jQuery会为您执行此操作.我的猜测是,字符串化(如果这是一个单词)正在做的事情混淆了ModelBinder.试试这个:

var obj = { 
    'user': $('#txtAdminUser').val(), 
    'password': $('#txtPassword').val(), 
    'isvalid': false 
};

$.ajax({
    data: obj,
    // rest of your settings...
});
Run Code Online (Sandbox Code Playgroud)


Pab*_*aus 1

尝试这个...用于测试目的:

改变这个:

public ActionResult IsUserAdmin(myCredential user) 
Run Code Online (Sandbox Code Playgroud)

为了这:

public ActionResult IsUserAdmin(myCredential item) 
Run Code Online (Sandbox Code Playgroud)

  • 如果这有效的话,我会非常生气。更新:它确实有效。我变成超级赛亚人足有十分钟了。 (2认同)