smurfo
smurfo

Reputation: 91

MVC Modelbinding jQuery Ajax

I have a Problem with my Modelbinding and i cant figure it out why it wouldnt work. Heres the Controller:

    public class ItemListController : Microsoft.AspNetCore.Mvc.Controller
{

    [HttpPost]
    public async Task<IActionResult> Create(string name)
    {           
        return View();
    }

}

this is the javascript

  var myObject = JSON.stringify("{Name: 'Test'}");

    var dataobject = 
    $.ajax({
        type: "POST",
        url: "/ItemList/Create",
        data: myObject,
        contentType: "application/json; charset=utf-8", dataType: "json",
        success: successFunc,
        error: errorFunc
    });

    function successFunc(data, status) {
        alert(data);
    }

    function errorFunc() {
        alert('error');
        console.log(JSON.stringify({ a: myData }));
    }
});

If tried nearly everything ive read. Can someone please let me know why binding is not happening?

Upvotes: 0

Views: 49

Answers (1)

Mustapha Larhrouch
Mustapha Larhrouch

Reputation: 3393

you can do it without JSON.stringify :

$.ajax({
    type: "POST",
    url: "/ItemList/Create",
    data: {Name: 'Test'},
    contentType: "application/json; charset=utf-8", dataType: "json",
    success: successFunc,
    error: errorFunc
});

function successFunc(data, status) {
    alert(data);
}

function errorFunc() {
    alert('error');
    console.log(JSON.stringify({ a: myData }));
}

Upvotes: 1

Related Questions