236

How do I render the partial view using jquery?

We can render the partial View like this:

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

How can we do the same using jquery?

3
  • You could have a look at below article as well. tugberkugurlu.com/archive/… It follows a different approach and enhances the way. Commented Sep 9, 2011 at 21:34
  • Stupid question. Is UserDetails a partial view as a cshtml page: UserDetails.cshtml? I am trying to load a partial view . And normally I would use: @Html.Partial("~/Views/PartialViews/FirstPartialViewTwo.cshtml") Commented Jan 4, 2018 at 3:39
  • 3
    @GeorgeGeschwend, Nothing is stupid here, till someone can respond to it. UserDetails(UserDetails.cshtml) is the Partial View inside the User Controller. As in the comments of the marked answer, its better to use Url.Action instead of hard coding the full path of the view. Commented Jan 11, 2018 at 13:35

8 Answers 8

303

You can't render a partial view using only jQuery. You can, however, call a method (action) that will render the partial view for you and add it to the page using jQuery/AJAX. In the below, we have a button click handler that loads the url for the action from a data attribute on the button and fires off a GET request to replace the DIV contained in the partial view with the updated contents.

$('.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);         
    });
});

where the user controller has an action named details that does:

public ActionResult Details( int id )
{
    var model = ...get user from db using id...

    return PartialView( "UserDetails", model );
}

This is assuming that your partial view is a container with the id detailsDiv so that you just replace the entire thing with the contents of the result of the call.

Parent View Button

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

User is controller name and details is action name in @Url.Action(). UserDetails partial view

<div id="detailsDiv">
    <!-- ...content... -->
</div>
Sign up to request clarification or add additional context in comments.

22 Comments

I keep getting bad request with this example code your gave. I copied as is and just changed the Controller action it should go to. I am not sure what "user" is for.
I just used some "likely" controller and action names since you didn't include any code that we could go by. Just replace "details" with your action and "user" with your controller name.
any idea how this would work with Razor? tried $.get( "@Url.Action(\"Manifest\",\"Upload\", new { id = " + key + " })", function(data) { $("<div/>").replaceWith(data); } );
@Patrick - I'd use single quotes (double is harder to read) for the JS. Regardless you don't need to "quote" the quote characters or construct a string -- just let the UrlHelper do it's work. See my updated example.
@Zapnologica - if you're reloading the entire table, you might need to reapply the plugin since the DOM elements it was originally connected to have been replaced. It might be better to connect it to a method that returns the data as JSON, datatables.net/examples/data_sources/server_side.html
|
163

I have used ajax load to do this:

$('#user_content').load('@Url.Action("UserDetails","User")');

12 Comments

Generally I think you're better off going with the Url.Action helper instead of hard-coding the path. This is going to break if your web site is in a subdirectory rather than at the root. Using the helper fixes that problem and allows you to add parameters with dynamically set values.
You could do $('#user_content').load('@Url.Content("~/User/UserDetails")') to get around that- i often use this method if i need the javascript to slap on the querystring params at the end of the url
In this answer, UserDetails is a name of an action, not a partial view, right?
@Prasad : Urls should always be evaluated using @Url.Action("ActionName","ControllerName", new { area = "AreaName" } ) instead doing Handcoding.
@PKKG. @Url.Action() only evaluates in Razor. this doesn't work if OP wants to put their code in a separate js file and reference it.
|
63

@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);
}

Comments

12

Another thing you can try (based on tvanfosson's answer) is this:

<div class="renderaction fade-in" 
    data-actionurl="@Url.Action("details","user", new { id = Model.ID } )"></div>

And then in the scripts section of your page:

<script type="text/javascript">
    $(function () {
        $(".renderaction").each(function (i, n) {
            var $n = $(n),
                url = $n.attr('data-actionurl'),
                $this = $(this);

            $.get(url, function (data) {
                $this.html(data);
            });
        });
    });

</script>

This renders your @Html.RenderAction using ajax.

And to make it all fansy sjmansy you can add a fade-in effect using this css:

/* make keyframes that tell the start state and the end state of our object */
@-webkit-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@-moz-keyframes fadeIn { from { opacity:0; } to { opacity:1; } }
@keyframes fadeIn { from { opacity:0; } to { opacity:1; } }

.fade-in {
    opacity: 0; /* make things invisible upon start */
    -webkit-animation: fadeIn ease-in 1; /* call our keyframe named fadeIn, use animattion ease-in and repeat it only 1 time */
    -moz-animation: fadeIn ease-in 1;
    -o-animation: fadeIn ease-in 1;
    animation: fadeIn ease-in 1;
    -webkit-animation-fill-mode: forwards; /* this makes sure that after animation is done we remain at the last keyframe value (opacity: 1)*/
    -o-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -webkit-animation-duration: 1s;
    -moz-animation-duration: 1s;
    -o-animation-duration: 1s;
    animation-duration: 1s;
}

Man I love mvc :-)

2 Comments

Why did you each function? How it works? Do u mena something like: data-actionurl="@Url.Action("details","user", new { id = Model.ID } data-actionurl="Another Action"?
No, the each function loops over all html elements that have the data-actionurl attribute and fills it by invoking an ajax request for the action method. So multiple <div class="renderaction fade-in" ...></div> elements.
10

You'll need to create an Action on your Controller that returns the rendered result of the "UserDetails" partial view or control. Then just use an Http Get or Post from jQuery to call the Action to get the rendered html to be displayed.

1 Comment

how to set time interval to refresh updated data in this jQuery function
6

Using standard Ajax call to achieve same result

        $.ajax({
            url: '@Url.Action("_SearchStudents")?NationalId=' + $('#NationalId').val(),
            type: 'GET',
            error: function (xhr) {
                alert('Error: ' + xhr.statusText);

            },
            success: function (result) {

                $('#divSearchResult').html(result);
            }
        });




public ActionResult _SearchStudents(string NationalId)
        {

           //.......

            return PartialView("_SearchStudents", model);
        }

Comments

1

I did it like this.

$(document).ready(function(){
    $("#yourid").click(function(){
        $(this).load('@Url.Action("Details")');
    });
});

Details Method:

public IActionResult Details()
        {

            return PartialView("Your Partial View");
        }

Comments

1

If you need to reference a dynamically generated value you can also append query string paramters after the @URL.Action like so:

    var id = $(this).attr('id');
    var value = $(this).attr('value');
    $('#user_content').load('@Url.Action("UserDetails","User")?Param1=' + id + "&Param2=" + value);


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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.