jquery - ajax posting from a partial view to controller is null -
i have baffling , quite silly problem.
i have weakly typed partial view in mvc4 application. on have button
<input type="button" class="btn btn-primary btn-lg" value="find" id="fej-find" />
i send jquery ajax call controller this
//searchedjob.num = $("#fej-jobnumber").val(); //var dto = { searchedjob: searchedjob }; var dto = { searchedjobnumber: $("#fej-jobnumber").val() }; $.ajax({ data: json.stringify(dto), type: 'post', url: '@url.action("searchjobs", "jobs")', success: function (msg) { return alert(msg); } });
firebug shows me this
but when debug, controller shows this.
something wrong code. be?
you don't need json.stringify
anything. pass value in data
parameter same key action parameter name (searchednumber
):
$.ajax({ url: '@url.action("searchjobs", "jobs")', type: 'post', data: { searchednumber: $("#fej-jobnumber").val() }, success: function (msg) { alert(msg); } });
also notice should not returning value success
callback.
you use json when want send larger , more complex payloads server, example entire models. example let's suppose have following view model:
public class myviewmodel { public int id { get; set; } public string name { get; set; } public ienumerable<string> tags { get; set; } }
which controller action takes parameter:
[httppost] public actionresult someaction(myviewmodel model) { ... }
now send json client:
var model = { id: 5, name: $('#some_input_field').val(), tags: [ "tag1", "tag2", "tag3" ] }; $.ajax({ url: '@url.action("somecontroller", "someaction")', data: json.stringify(model), contenttype: 'application/json', success: function(result) { alert(result); } });
notice how in case need set proper content-type request header application/json
default model binder on server able automatically deserialize request body payload corresponding view model.
Comments
Post a Comment