yopez83 yopez83 - 1 year ago 127
jQuery Question

Load a Partial View using jQuery .load() and no Razor

I have a View which is the container for a PartialView. Let's say a Customer - Orders relation. The View should received a

whereas the PartialView a collection of Orders, such as

I basically have two ways of doing this (not to mention Angular), either Razor or jQuery. With Razor was pretty straightforward by utilizing
@Html.Partial("_CustomerOrdersPartial", Model.Orders)
. But let's assume I cannot use Razor syntax and here it is how I ended up posting this question. I have read many posts on this matter but, most of them (not to mention all), suggest to use
$("#container").load('@Url.Action("ActionName", new { parameterX = valueY }))
. Then here are my questions:

  • Why to mix Razor and jQuery?

  • Is this the only way?

  • Is there any way to call the View and pass the model?

The last question has to do with the fact that the above code requires an action on the server-side to be called, whereas the
@Html.Partial("_CustomerOrdersPartial", Model.Orders)
mentioned above will just call the View (client-side) and send the given Model in.

Any idea on how to solve this would be really helpful.

Thanks in advance for your time and thoughts.

Answer Source

This code should do it. The trick is to acquire the URL and then make sure you get the parameter list right. I used a little Razor to get the URL but you don't have to. Also, If you fail to match the parameter list, your call will not even be acknowledged. You have been warned. I tried to name every thing in a way that helps.

    var url = '/controllerName/ActionName';
    $('#pnlFillMee').load(url, {NameOfParam: $('#elementID').val() },
    function () {CallMeAfterLoadComplete(); });

Here's a real world example I use at work. ReviewInfo is an action in the controller associated with this page. It returns a partialview result.

$(document).ready(function () {
var url = '/supervisor/reviewinfo';
$('#pnlReviewInfo').load(url, { FCUName: $('#FCU').children(':selected').text(), AccountsFromDate: $('#AccountsFrom').val()}, function () {

This goes somewhere on your form.

<div id="pnlReviewInfo" style="width: 85%"></div>

EDIT: I would also look up the other jQuery functions like $.get, $.post and $.ajax which are more specialized versions of $.load. and see this link which might answer all your questions about passing models:
Pass Model To Controller using Jquery/Ajax

Hope this helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download