Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render Partial View with Object Model using jquery / Ajax

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?

like image 842
Kevin Scheidt Avatar asked Sep 11 '26 11:09

Kevin Scheidt


1 Answers

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),
like image 112
Matt Bodily Avatar answered Sep 13 '26 01:09

Matt Bodily