Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Similar JSON requests but one sends null object

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?

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.

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

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

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

route values:

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 shows item is a JSON object, as expected. Also a "stringified" obj. Debugging server-side code shows that myCredential parameter is null.

like image 967
Captain Kenpachi Avatar asked Dec 19 '12 13:12

Captain Kenpachi


People also ask

What is response JSON in Python?

response.json () returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.

How to get the exact value of invitee_ID from JSON response?

It seems that because id is a dynamically changing value, even if you parse the JSON response, the property name is always changing, so you can't get the exact value. It seems that the id value we need in the results, you could take this id first, and then use it to get invitee_id.

What is the use of request in Python?

Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc.


2 Answers

You do not need to stringify the object as the jQuery will do this for you. My guess would be that something the stringification (if that's a word) is doing is confusing the ModelBinder. Try this:

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

$.ajax({
    data: obj,
    // rest of your settings...
});
like image 185
Rory McCrossan Avatar answered Sep 25 '22 23:09

Rory McCrossan


Try this...for testing purposes:

change this:

public ActionResult IsUserAdmin(myCredential user) 

for this:

public ActionResult IsUserAdmin(myCredential item) 
like image 21
Pablo Claus Avatar answered Sep 26 '22 23:09

Pablo Claus