Skip to content Skip to sidebar Skip to footer

Ajax Passing Null Value To Controller

I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total whe

Solution 1:

From browser console, this

$.ajax({
        cache: false,
        type: "get",
        contentType: "application/json; charset=utf-8",
        url: 'http://google.com',
        data: JSON.stringify({ idp: 1, id: 2 }),
        dataType: "json",
        aysnc: false,
        success: function (data1) {
           console.log(data1)

        }
    });

returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect

and without stringify

$.ajax({
        cache: false,
        type: "get",
        contentType: "application/json; charset=utf-8",
        url: 'http://google.com',
        data: { idp: 1, id: 2 },
        dataType: "json",
        aysnc: false,
        success: function (data1) {
           console.log(data1)

        }
    });

returns http://google.com/?idp=1&id=2&_=1440696381239 (see Network tab)

So don't use JSON.stringify

Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params & data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action

But Don't believe me, check it yourself

chrome dev console is your friend


Solution 2:

By removing the contentType: "application/json; charset=utf-8 and dataType: "json" it worked for me. Otherwise, I was always getting value = null in the controller action. My code for calling ajax with data is now:

 $(function () {
    $.noConflict();
    $.ajax({
        type: "POST",
        url: "../Case/AjaxMethodForUpdate",
        data: {typ: $('#typeID').val()},
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        },
        error: function (response) {
            alert(response.d);
        }
    }); 

Solution 3:

You can just put it like

var dataReq={ idp: previous, id: sel };
data: dataReq

And no need to use dataType and contentType.


Post a Comment for "Ajax Passing Null Value To Controller"