up vote 9 down vote favorite
7

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?

link|flag

77% accept rate

3 Answers

up vote 17 down vote

You can't. You can, however, call a method (action) that will render the partial view for you.

$.get( '<%= Url.Action("details","user", new { id = Model.ID } %>',
       function(data) {
           $('#detailsDiv').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 Partial( "UserDetails", model );
}
link|flag
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. – chobo2 Nov 8 '09 at 5:55
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. – tvanfosson Nov 8 '09 at 13:04
Thanks again for a great answer tvanfosson. – Mike Nov 3 at 19:28
up vote 13 down vote accepted

I have used ajax load to do this:

$('#user_content').load('/User/UserDetails');
link|flag
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. – tvanfosson Nov 3 at 19:33
up vote 2 down vote

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.

link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.