3

My current code looks like

<!-- some html -->
{
    // some code
    @Html.Partial("~/Views/AdminUser/Main.cshtml", Model.AdminUserModel)
}

however, i need this to instead be an ajax call. How do I do an jquery ajax call where the model is included in the call?

tereško
  • 58,060
  • 25
  • 98
  • 150
Kevin Scheidt
  • 95
  • 3
  • 10
  • What you could do is make an ajax call with a url query. Set the variables based on your query string. – fassetar Aug 15 '13 at 15:32
  • problem with that solution is the model could be huge. mainly need to know how to pass the model. – Kevin Scheidt Aug 15 '13 at 16:35
  • was thinking you could possibly make the ajax call include a json (stringify?) version of the model and on the back-end put the model back into the object? not quite sure how. – Kevin Scheidt Aug 15 '13 at 16:37

1 Answers1

3

How I do it is an ajax call passing the id:

$.ajax({
    url: "@(Url.Action("Action", "Controller", new { id = "----" }))/".replace("----", id),
    type: "POST",
    cache: false,
    async: true,
    success: function (result) {
         $(".Class").html(result);
    }
});

and then in your controller have the action set up like

public PartialViewResult Action(string id)
{
     //Build your model
     return PartialView("_PartialName", model);
}

if you do need to pass a model to the controller through ajax, if you create a jquery object that has the same fields as the model and stringify and pass it, it will come through correctly.

var toSend = {};
toSend.ID = id;
toSend.Name = name; 

etc, then in the ajax call

data: JSON.stringify(toSend),
Matt Bodily
  • 6,403
  • 4
  • 29
  • 48