1

I have a View which is the container for a PartialView. Let's say a Customer - Orders relation. The View should received a CustomerViewModel whereas the PartialView a collection of Orders, such as IEnumerable<OrderViewModel>.

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.

dotnetspark
  • 551
  • 4
  • 23
  • 1
    Because using `'@Url.Action()` will always ensure your url is correctly generated. –  Jul 22 '16 at 03:14
  • `@Url.Action` itself is a Razor syntax that generate URL based from controller and action method. Keep in mind that partial view created from a callback, without refreshing entire page. – Tetsuya Yamamoto Jul 22 '16 at 03:22
  • Exactly what Stephen said. Your URLs are maintained by the MVC routing infrastructure. One of its main purposes is to ensure that there is only 1 place in the application to change if you want to change a URL later. Using `@Url.Action` ensures the URL is generated from routing rather than being hard coded in your view. – NightOwl888 Jul 22 '16 at 03:23
  • @stephen-muecke I agree `@Url.Action` will ensure the url is consistent, just as asp-controller tag helper does in ASP.NET Core but, still Url.Action will go server-side whereas `@Html.Partial` will stay client-side. Am I wrong? – dotnetspark Jul 22 '16 at 03:53
  • 1
    `@Html.Partial()` is server side code, not client side code. Not really sure what your asking here. `$.load()` is client side code. Why in the world would you send your model to the view then send it back again, unchanged, to the server to get a partial view based on it instead or just rendering it in the first place. You typically use `$.load()` (or any ajax method) in response to client side events –  Jul 22 '16 at 04:05
  • Thanks for clarifying @stephen-muecke. Let me make myself clear about my question. What I'm trying to find out is, when using `@Html.Partial()` why are the parameters to send in, the view_name and/or a model? meaning, there is no action method. Whereas, when using `$.load()` the parameter is the URL to an action. I mean, there is no way to inject a partial view through jQuery without the need of an action method. – dotnetspark Jul 22 '16 at 05:31
  • 1
    Because `Html.Partial()` is server side code. The method searches for a view with the matching name and adds it the the html being generated on the server side. It does not need a url because its already on the server. Using `.load()` however is client side code. The client has no knowledge of what is on the server unless it calls the server to return something, and to do that, you need to provide a url. –  Jul 22 '16 at 05:47
  • thanks @StephenMuecke – dotnetspark Jul 22 '16 at 05:57

3 Answers3

2

my solution is:

function ReturnPanel(div, panel) {

    $.ajax({
        type: "POST",
        url: "@Url.Action("GetPanel", "ControllerName")",
        data: JSON.stringify({ 'idCurso': idCurso, 'panel': panel }),            
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            $("#" + div).html(response);
        },
        error: function (xhr, status, errorThrown) {
            //Here the status code can be retrieved like;                
            alert("Error: status = " + xhr.status + " Descripcion =" + xhr.responseText);
        }
    })
}

in cs.

 [HttpPost]
    public ActionResult GetPanel(int idCurso, string panel)
    {
        Contenido contenido = new Contenido();
        contenido.IdCurso = idCurso;
        return PartialView(panel, contenido);
    }
Mario Villanueva
  • 327
  • 3
  • 10
1

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 () {
                    InitializeTabs(true); 
                });
});

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

Community
  • 1
  • 1
  • Thanks but, I still need to have an action method while when using `@Html.Partial()` I don't have to. I am looking for a way to inject a partial view into a view using jQuery without calling an action method. – dotnetspark Jul 22 '16 at 05:38
  • 1
    well if you do this alert(url); in the code you will see that Url.Action is simply acquiring the controller name which is part of the routing system in MVC. so URL turns out to be '/controllerName/actionName' Are you just trying to figure out the URL without using Razor. No matter how you slice it JQuery.Load needs the URL. – Charles McIntosh Jul 22 '16 at 13:20
  • 1
    I have updated my answer. After a more in-depth reading of your question. – Charles McIntosh Jul 22 '16 at 13:52
  • Thanks @charles-mcinstosh – dotnetspark Jul 28 '16 at 01:53
0

wrapping up this question and thanks to @stephen-muecke and @charles-mcintosh for their help:

  • Using @Html.Partial(partialViewName) the server returns a string resulting from the partial view passed in. Preferred method if you need to manipulate the partial before being displayed. Otherwise, using @Html.RenderPartial(partialViewName) will write into the stream output sent to the browser, the HTML code from the given partial.
  • As per jQuery API, $(elem).load(url[,data][,complete]) will place the returned HTML into the matching element. Thus, it requires an action method for the given url.
  • If for whatever reason Razor cannot be used on the UI, chances are you would likely end up either hard-coding the url like in the sample code provided above by @charles-mcintosh or using Angular.
dotnetspark
  • 551
  • 4
  • 23