Sending String Data to MVC Controller using jQuery $.ajax() and $.post()
Asked Answered
V

7

19

There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried:

$.post("/Journal/SaveEntry", JSONstring);

And here is the ajax method I tried:

$.ajax({
    url: "/Journal/SaveEntry",
    type: "POST",
    data: JSONstring
});

Here is my Controller:

public void SaveEntry(string data)
{
    string somethingElse = data;
}

For background, I serialized a JSON object using JSON.stringify(), and this has been successful. I'm trying to send it to my Controller to Deserialize() it. But as I said, the string is arriving as null each time. Any ideas?

Thanks very much.

UPDATE: It was answered that my problem was that I was not using a key/value pair as a parameter to $.post(). So I tried this, but the string still arrived at the Controller as null:

$.post("/Journal/SaveEntry", { "jsonData": JSONstring });
Veratrine answered 3/12, 2009 at 21:24 Comment(1)
in response to your update... Can you firebug it? what is actually being sent as the request to the server in your firebug console?Pennell
V
26

Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:

public void SaveEntry(string jsonData)

and my post action in JS looks like:

$.post("/Journal/SaveEntry", { jsonData: JSONstring });

JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON plugin offered at json.org. So:

JSONstring = JSON.stringify(journalEntry);  // journalEntry is my JSON object

So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.

Veratrine answered 9/12, 2009 at 15:20 Comment(0)
P
5

Final Answer:

It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.

Actually, make sure youre using the right key name that your serverside code is looking for as well as per Olek's example - ie. if youre code is looking for the variable data then you need to use data as your key. – prodigitalson 6 hours ago

@prodigitalson, that worked. The variable names weren't lining up. Will you post a second answer so I can accept it? Thanks. – Mega Matt 6 hours ago

So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.


the data argument has to be key value pair

$.post("/Journal/SaveEntry", {"JSONString": JSONstring});
Pennell answered 3/12, 2009 at 21:54 Comment(5)
@prodigitalson, I agree that this is one option, but the documentation at docs.jquery.com/Ajax/jQuery.post says that it will accept key/value pairs (Map) or a String. So I'm left a little confused...Veratrine
@Mega Matt: If you use a string i would assume it needs to be in standard query string format ie. JSONString=mySerializedDataStruct&var2=myothervar. In order to retrieve it on the server side the variable hase to have a name.Pennell
@prodigitalson, tried using the method you answered above with no success. See my edit above.Veratrine
yeah i jsut saw that and replied directly on your question... Can you use firebug to see whats being sent in the request? (or any other method thats going to see the actual http request thats sent before any server side filtering or anything.)Pennell
@Mega Matt, see the bottom of this page: getfirebug.com/net.html It has sample screenshot and text explanation, I hope this will help.Intramolecular
I
2

It seems dataType is missed. You may also set contentType just in case. Would you try this version?

$.ajax({
    url: '/Journal/SaveEntry',
    type: 'POST',
    data: JSONstring,
    dataType: 'json',
    contentType: 'application/json; charset=utf-8'
});

Cheers.

Intramolecular answered 3/12, 2009 at 21:56 Comment(5)
@Oleksandr Bernatskyi, but should the dataType be 'json' when I'm sending a string over? This is not a JSON object, simply a string...Veratrine
Oh, I see. @Pennell said the right thing actually - each variable should have a name. Maybe this will work? $.post("/Journal/SaveEntry", { "data": JSONstring });Intramolecular
Actually, make sure youre using the right key name that your serverside code is looking for as well as per Olek's example - ie. if youre code is looking for the variable data then you need to use data as your key.Pennell
@prodigitalson, that worked. The variable names weren't lining up. Will you post a second answer so I can accept it? Thanks.Veratrine
@Mega Matt I jsut edited my original response to have the final answer - you werent clear though - what was your final format for sending the data was it: {var: value} or 'var=value' or some other format?Pennell
B
1

Thanks for answer this solve my nightmare.

My grid

..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();

<script type="text/javascript">
function onRowSelected(e) {
        id = e.row.cells[0].innerHTML;
        $.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
    }
</script>

my controller

public ActionResult GridSelectionCommand(string id)
{
     //Here i do what ever i need to do
}
Bendy answered 30/9, 2011 at 10:25 Comment(0)
N
0

The Way is here.

If you want specify

dataType: 'json'

Then use,

$('#ddlIssueType').change(function () {


            var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };

            $.ajax({
                type: 'POST',
                url: '@Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
                data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
                dataType: 'json',
                cache: false,
                success: function (data) {
                    $('#ddlStoreLocation').get(0).options.length = 0;
                    $('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');

                    $.map(data, function (item) {
                        $('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
                    });
                },
                error: function () {
                    alert("Connection Failed. Please Try Again");
                }
            });

If you do not specify

dataType: 'json'

Then use

$('#ddlItemType').change(function () {

        $.ajax({
            type: 'POST',
            url: '@Url.Action("IssueTypeList", "SalesDept")',
            data: { itemTypeId: this.value },
            cache: false,
            success: function (data) {
                $('#ddlIssueType').get(0).options.length = 0;
                $('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');

                $.map(data, function (item) {
                    $('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
                });
            },
            error: function () {
                alert("Connection Failed. Please Try Again");
            }
        });

If you want specify

dataType: 'json' and contentType: 'application/json; charset=utf-8'

Then Use

$.ajax({
            type: 'POST',
            url: '@Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
            data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            cache: false,
            success: function (data) {

                $('#ddlAvailAbleItemSerials').get(0).options.length = 0;
                $('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');

                $.map(data, function (item) {
                    $('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
                });
            },
            error: function () {
                alert("Connection Failed. Please Try Again.");
            }
        });
Noaccount answered 4/3, 2013 at 5:8 Comment(0)
I
0

If you still can't get it to work, try checking the page URL you are calling the $.post from.

In my case I was calling this method from localhost:61965/Example and my code was:

$.post('Api/Example/New', { jsonData: jsonData });

Firefox sent this request to localhost:61965/Example/Api/Example/New, which is why my request didn't work.

Ingravescent answered 21/1, 2018 at 13:52 Comment(0)
O
0

In this approach, on the controller’s action parameter, I was receiving a null:

document.addEventListener("DOMContentLoaded", function () {
            
        submitBtn.addEventListener("click",function(){
                var JSONstring = JSON.stringify(toSend);
                   
            $.ajax({
                url: "/Sales/Create",
                method:"POST",
                   
                dataType:"json",
                    contentType: 'application/json;charset=utf-8',
                    data: { "jsonData": JSONstring }
                   
                success: function (response) {
                    console.log(JSONstring);
                    window.location.href = '/Sales/Index';
                },
                error: function (error) {
                    console.error(error);
                }
            });
        })
});

But after I switch to this approach, my problem is solved and I started received my JSON. (Take this as a sample to solve your problem.)

        document.addEventListener("DOMContentLoaded", function () {
                // Assuming submitBtn is properly defined
                submitBtn.addEventListener("click", function () {
                  // Make sure to define toSend with appropriate data
                    var JSONstring = JSON.stringify(toSend);
        
                    $.post("/Sales/Create", { "jsonData": JSONstring }, function (response) {
                        console.log(JSONstring); // Fix variable name
                        window.location.href = '/Sales/Index';
                    }, 'json')
                        .fail(function (error) {
                            console.error(error.responseText); // Log the specific error message
                        });
                });
            });

In your controller:

/*[ValidateAntiForgeryToken]*/
[HttpPost]
public JsonResult Create(string jsonData)  
{  
    //write your own code here
}

Notes: 1. If you didn't send a token and the [ValidateAntiForgeryToken] attribute exists, comment it out or erase it or learn how to send a validation token. 2. The parameter name in the action controller should match the key in my JSON—in my case jsonData.

Ogre answered 27/11, 2023 at 18:36 Comment(1)
@jeremyCaney this answer extends what the most voted answer, i added the two callback function that handle error and success and the expected data type of the response. also i clarify that the first approach didn't achieve what i want ,also i put notesOgre

© 2022 - 2024 — McMap. All rights reserved.