javascript - MVC send Model with ajax -


i having issue when trying send data save method using ajax. way because reusing form in several screens rendering partial page using same save function.

the problem having when way work , sends save function, serialized json made when page loads , doesn't updated values. updated values sent ajax, ideally without having capture values of every field on page.

below code using work sending save method original values listed in model

$("#save").click(function () {     var form = $('#form');      if (form.valid()) {         var data = '@html.raw(newtonsoft.json.jsonconvert.serializeobject(@model))';          $.ajax({             url: "/save",             type: 'post',             data: json.stringify({ modeljson: data }),             contenttype: 'application/json',             success: function (result) {                 savefade();             }         });     }      return false; }); 

firstly, please use .done, .fail, , .always methods on deferred jquery's $.ajax methods returns instead of success. secondly, not use razor methods directly in javascript, single quote character ' may cause syntax errors. instead close data in hidden div id, example: <div id="formdata">@html.raw(newtonsoft.json.jsonconvert.serializeobject(@model))</div>, in javascript do: var data = $('#formdata').html();. way can move scripts seperate .js file.

answering problem, must send actual form using ajax controller method. close fields in form, assign id form @using(html.beginform("method", "controller", formmethod.post, new { id = "myform" })), , send using ajax:

    $("#save").click(function () {         var form = $('#form');          if (form.valid()) {             var data = form.serialize();              $.ajax({                 url: "/save", //you can action attribute form using form.attr('action')                 type: 'post',                 data: data             }).done(function (result) {                 savefade();             });          }           return false;      }); 

good tutorial forms in asp.net mvc: http://blog.michaelckennedy.net/2012/01/20/building-asp-net-mvc-forms-with-razor/


Comments

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -