-1

Can I post an MVC model using AJAX, like:

 $.ajax ({
     //what elements are important?
     data: '@Model.Product',
     success: function(data){
        $("#divProducts").html(data);
     }
 }

I want to avoid changing the model into JSON or JavaScript objects because I would still have to load them from the fields on the page. It would be easier if I use the standard @Html.TextboxFor stuff to fill the model fields and then post the whole model with AJAX.

Dean.DePue
  • 1,013
  • 1
  • 21
  • 45
  • yes. you certainly can do that. – Daniel A. White Jan 25 '15 at 16:58
  • @DanielA.White How can I do that? Just the way I've listed? – Dean.DePue Jan 25 '15 at 17:08
  • theres plenty of examples out there. – Daniel A. White Jan 25 '15 at 17:09
  • You question is not clear. Posting back `@Model` would only post back the original model (a bit pointless). If you mean post back you form values then you can use the jquery [serialize()](http://api.jquery.com/serialize/) method –  Jan 25 '15 at 22:32
  • @StephenMuecke - so the model as it has changed with values or text fields in the form would not be reflected in the ajax post of data? – Dean.DePue Jan 25 '15 at 23:28
  • Not if your used `@Model` because razor code is parsed on the server. Check the html generated by `var myModel = JSON.parse('@Html.Raw(Json.Encode(Model.Product))');` - its the original model and the value of `myModel` does not change just because you change the value in a text box. You need to serialize the form and post that back using ajax. –  Jan 25 '15 at 23:37

2 Answers2

0

You can serialize the model into JSON and then post the serialized JSON object to server.

var productModel= @Html.Raw(Json.Encode(Model.Product))
$.ajax ({
     //send the serialized JSON 
     data: JSON.stringify(productModel),
     success: function(data){
        $("#divProducts").html(data);
     }
 }
Vijay
  • 2,965
  • 1
  • 15
  • 24
  • 1
    That would be rather pointless - its just posting back exactly the same values (unchanged) that were sent to the view in the first place. –  Jan 25 '15 at 22:11
0

The simple answer is to not use the JSON.Encode method but to simply fill the loaded model with values and then use $.serializeArray() with the class of the fields you want to load the model with.

Dean.DePue
  • 1,013
  • 1
  • 21
  • 45