0

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?

1 Answer 1

1

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 }));
}
Sign up to request clarification or add additional context in comments.

5 Comments

unfortunately not... also tried {'Name' : 'test'} {Name:test} and so on
you need to remove dataType: "json" bacause the action return a view(html) not json
when i look at the networktraffic there is a payload Name:"Test" but the string in the conrtoller method keeps null
try to remove contentType: "application/json; charset=utf-8"
when you use it the action bind only objects

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.