类似的JSON请求,但有一个发送空对象 [英] Similar JSON requests but one sends null object

查看:148
本文介绍了类似的JSON请求,但有一个发送空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发ASP.NET的MVC4。
我在我的code,它提交了一个JSON物体的两个JSON请求。他们中的一个正常工作,另外通过一个空的某些原因。任何想法?

I am developing on ASP.NET MVC4. I have two JSON requests in my code that submits a JSON object. One of them works fine, the other passes a null for some reason. Any ideas?

注意:在这两种情况下,实际上在请求到达预期的控制器。这只是第二个传递,而不是我很好地填充对象的NULL。

Note: in both instances, the request in fact reaches the intended controller. It's just that the second one passes a NULL, instead of my nicely populated object.

工作的javascript:

working 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*/);
                }
            });
        });

工作控制器动作:

working controller action:

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

这传递一个NULL对象中的JavaScript:

javascript that passes a NULL object:

$('#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);
                }
            });

        });

控制器操作接收一个空对象:

controller action that receives a null object:

[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

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:

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对象,符合市场预期。同样是字符串化的obj。
调试服务器端code表示myCredential参数为null。

Firebug shows item is a JSON object, as expected. Also a "stringified" obj. Debugging server-side code shows that myCredential parameter is null.

推荐答案

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

Try this...for testing purposes:

更改此:

public ActionResult IsUserAdmin(myCredential user) 

本:

public ActionResult IsUserAdmin(myCredential item) 

这篇关于类似的JSON请求,但有一个发送空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆