Render Partial View Using jQuery in ASP.NET MVC

后端 未结 8 2063
有刺的猬
有刺的猬 2020-11-22 11:13

How do I render the partial view using jquery?

We can render the partial View like this:

<% Html.RenderPartial(\"UserDetails\"); %>
         


        
8条回答
  •  粉色の甜心
    2020-11-22 11:37

    @tvanfosson rocks with his answer.

    However, I would suggest an improvement within js and a small controller check.

    When we use @Url helper to call an action, we are going to receive a formatted html. It would be better to update the content (.html) not the actual element (.replaceWith).

    More about at: What's the difference between jQuery's replaceWith() and html()?

    $.get( '@Url.Action("details","user", new { id = Model.ID } )', function(data) {
        $('#detailsDiv').html(data);
    }); 
    

    This is specially useful in trees, where the content can be changed several times.

    At the controller we can reuse the action depending on requester:

    public ActionResult Details( int id )
    {
        var model = GetFooModel();
        if (Request.IsAjaxRequest())
        {
            return PartialView( "UserDetails", model );
        }
        return View(model);
    }
    

提交回复
热议问题