Home  >  Article  >  Web Front-end  >  How to Render a Partial View Using jQuery in ASP.NET MVC?

How to Render a Partial View Using jQuery in ASP.NET MVC?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-05 08:27:02602browse

How to Render a Partial View Using jQuery in ASP.NET MVC?

Render Partial View Using jQuery in ASP.NET MVC

In ASP.NET MVC, partial views are commonly rendered using the Html.RenderPartial() method. However, there may be scenarios where you need to render the partial view using jQuery instead.

Approach Using jQuery and Ajax

To render a partial view using jQuery, you can do the following:

  1. Create an Action Method: Define an action method in your controller to return the partial view.
  2. Bind a jQuery Event Handler: Bind a click event handler to a button or link on your page.
  3. Call the Action Method: Inside the event handler, use $.get() or $.post() to send an Ajax request to the action method.
  4. Replace Partial View Div: When the action method returns a partial view, use $.replaceWith() or $.html() to replace the existing content of the partial view div on the page.

Example:

<code class="javascript">$('.js-reload-details').on('click', function(evt) {
    evt.preventDefault();
    evt.stopPropagation();

    var $detailDiv = $('#detailsDiv'),
        url = $(this).data('url');

    $.get(url, function(data) {
        $detailDiv.replaceWith(data);         
    });
});</code>

In this example, a button with the class js-reload-details triggers the click event handler. The event handler loads the partial view using $.get() and replaces the contents of the div with id detailsDiv with the returned HTML.

Controller Action:

<code class="csharp">public ActionResult Details( int id )
{
    var model = ...get user from db using id...

    return PartialView( "UserDetails", model );
}</code>

Parent View Button:

<code class="html"><button data-url='@Url.Action("details","user", new { id = Model.ID } )'
         class="js-reload-details">Reload</button></code>

UserDetails Partial View:

<code class="html"><div id="detailsDiv">
    <!-- ...content... -->
</div></code>

The above is the detailed content of How to Render a Partial View Using jQuery in ASP.NET MVC?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn