JQuery Ajax stops working after adding .submit(function() { } -
the original issue jquery ajax won't call succuess after hitting c# method. looking @ similar issue here: jquery ajax not returning success see solution add:
$(parentform).submit(function(event) { event.preventdefault();`
however, after doing this, ajax code doesn't seem execute. hit js function though, stops before executes ajax code.
my html code looks this:
@{ const string formid = "parentform"; } @using (html.beginform("editchannel", "channel", formmethod.post, new { id = formid })) { html.renderpartial("editchannelform", model); <br /><br /> <input type="button" value="save" onclick="editchannel('@model.channelviewmodel.id', @formid)" /> }
i submit form in js code (when button above clicked) looks this:
function editchannel(channelid, parentform) { $(parentform).submit(function(event) { event.preventdefault(); $.ajax({ url: "/channel/editchannel/", type: "post", cache: false, data: { id: channelid, updatedmodel: parentform }, success: function(msg) { alert("msg: " + msg); if (msg === "changeofsensitivedata") { showalertonchangeofsensitivedata('sensitivdatamsgdiv'); } else { alert("else"); } }, error: function(msg) { alert("error"); } }); }); }
i hit js function, ajax never executes, , therefore not calling c# method. if this:
function editchannel(channelid, parentform) { $(parentform).submit() ...
then ajax code executes , hits c# method, never hits success function.
the c# looks this:
[httppost] public actionresult editchannel(int id, channelandlocationviewmodel updatedmodel) { updatedmodel.locationitemviewmodels = getlocationitems(); if (modelstate.isvalid) { channelmodel channel = null; using (var context = new maanegriscontext()) { var oldunit = context.channels.where(c => c.id == id).select(c => c.unit).singleordefault(); var newunit = updatedmodel.channelviewmodel.unit; if (oldunit != null && !oldunit.equals(newunit)) { return content("changeofsensitivedata"); } ...
you current code passing models channelviewmodel.id
value , string value "parentform"
editchannel()
method, passes string controllers editchannel()
method. parameter updatedmodel
complex object of type channelandlocationviewmodel
cannot bound string binding fails , value of updatedmodel
null.
remove onclick
attribute , change button to
<input type="button" id="save" value="save" />
then modify script to
var url = '@url.action("editchannel", "channel")'; var channelid = '@model.channelviewmodel.id $('#save').click(function() { // serialize form , add additional parameter var data = $('form').serialize() + '&' + $.param({ id: channelid }); $.post(url, data, function(msg) { alert("msg: " + msg); .... }); });
alternatively, include @html.hiddenfor(m => m.channelviewmodel.id)
in view , use var data = $('form').serialize()
value channelviewmodel.id
included in post , int id
parameter not required in controller method (it bound in updatedmodel
parameter).
Comments
Post a Comment