asp.net mvc 3 - How to do Jquery ajax post to controller mvc -
i can't figure out not doing right,from viewmodel,i try grab user {**tousername , messagebody},#tousername** correctly sent while #body null in controller when debug .i have following jquery code:
$("#sendmessage").click(function () { var message = grabmessage(); var jsondata = json.stringify(message, null, 2); $.ajax({ url: '@url.content("~/message/compose/")', type: 'post', data: jsondata, datatype: 'json', contenttype: 'application/json; charset=utf-8', success: function () { $('#default_message').append("message sent "); switchtosentmessagestab(); }, error: function (request, status, err) { alert(status); alert(err); } }); return false; }); function switchtosentmessagestab() { $('a[href="#default_message"]').click(); } function grabmessage() { var touser = $("#tousername").val(); var text = $("#body").val(); var result = { body: text, tousername: touser }; return result; } });
and razer view:
@using (html.beginform()) { @html.validationsummary(true) <div class="editor-label"> @html.labelfor(model => model.tousername) </div> <div class="editor-field"> @html.editorfor(model => model.tousername, new { @class ="autocomplete"}) @html.validationmessagefor(model => model.tousername) </div> <div class="editor-field"> @html.editorfor(model => model.body) @html.validationmessagefor(model => model.body) </div> <p> <input id="sendmessage" type="submit" value="send" /> </p>
} , controller action:
[httppost] public actionresult compose(privatemessageviewmodel m) { if (user.identity.isauthenticated ) { if (modelstate.isvalid) { var tousername = users.profiles.first(x => x.username == m.tousername); privatemessage message = new privatemessage { //do stuff here: }; db.sendmessage(message); return redirecttoaction(//some view here...) } } return partialview(m); }
Comments
Post a Comment