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

2024-01-27

我正在 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 参数为 null。


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

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

$.ajax({
    data: obj,
    // rest of your settings...
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

类似的 JSON 请求,但发送 null 对象 的相关文章

随机推荐