6

ASP.NETMVC4で開発しています。コードにJSONオブジェクトを送信する2つのJSONリクエストがあります。それらの1つは正常に動作し、もう1つは何らかの理由でnullを渡します。何か案は?

注:どちらの場合も、リクエストは実際には目的のコントローラーに到達します。うまく配置されたオブジェクトの代わりに、2番目のものが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);
                }
            });

        });

nullオブジェクトを受け取るコントローラーアクション:

[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は、予想どおり、アイテムがJSONオブジェクトであることを示しています。また、「文字列化された」オブジェクト。サーバー側のコードをデバッグすると、myCredentialパラメーターがnullであることが示されます。

4

2 に答える 2

6

jQuery がこれを行うため、オブジェクトを文字列化する必要はありません。私の推測では、文字列化 (それが単語の場合) が行っていることは、ModelBinder を混乱させることです。これを試して:

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

$.ajax({
    data: obj,
    // rest of your settings...
});
于 2012-12-19T13:29:23.800 に答える
1

これを試してください...テスト目的で:

これを変える:

public ActionResult IsUserAdmin(myCredential user) 

このため:

public ActionResult IsUserAdmin(myCredential item) 
于 2012-12-19T18:37:59.967 に答える