D-W
D-W

Reputation: 5341

jQuery ajax send data - ASP.Net MVC

Trying to pass an id back to the controller (btw the id is not null) Controller thinks it gets null.

var url = '@Url.Action("Delete")';

$.ajax({
    url: url,
    async: false,
    // have also tried data:clientId and data:[clientId]
    data: { id: clientId },
    type: 'POST',
});

Controller

public ActionResult Delete(string id)
{
    // Do something
}

Upvotes: 0

Views: 1872

Answers (1)

ramiramilu
ramiramilu

Reputation: 17182

Here goes the implementation:

public ActionResult Delete(string id)
{
    return null;
}

And say your jQuery code and HTML is as below:

<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
    function submitForm() {
        var model = new Object();
        model.Name = "Rami";

        jQuery.ajax({
            type: "POST",
            url: "@Url.Action("Delete")",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ id: model.Name }),
            success: function (data) { alert(data); },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
    }
</script>

<input type="button" value="Click" onclick="submitForm()"/>

When you execute the code:

enter image description here

Upvotes: 1

Related Questions