简体   繁体   中英

MVC partial View and controller code

I don't understand how a partial view is handled by controller, is it the same as a view? I made an example and it seems that partial view controller is never used

This is the example

Main View (test.cshtml):

<h2>Main View</h2>
@Html.Partial("_Partial", new { myNumber = 11 })

Partial View (_Partial.cshtml):

<h3>partial view</h3>
<p>my number is @Html.ViewBag.myNumber</p>

Controller (EtlMessagesController)

public ActionResult Test() {
    return View();
}

public ActionResult _Partial(int myNumber) {
    ViewBag.myNumber = myNumber;

    return PartialView();
}

When i invoke the main view I expect

Main View

partial view

my number is 11

But the nummber 11 is not written. Am I missing something?

Here your pass anonymous model to the partial view:

<h2>Main View</h2>
@Html.Partial("_Partial", new { myNumber = 11 })

Try use explicit model class or just int :

<h2>Main View</h2>
@Html.Partial("_Partial", 11)

Then you can use @model keyword in the partial view:

@model int
<h3>partial view</h3>
<p>my number is @Model</p>

As for:

public ActionResult _Partial(int myNumber) {
    ViewBag.myNumber = myNumber;

    return View();
}

You should use:

public ActionResult _Partial(int myNumber) {
    return PartialView("_Partial", 11);
}

The method PartialView can be used in AJAX scenarios to render a part of a HTML-page.

I found 3 ways thank to comments and answers:

  1. @Html.Action (thank to Stephen Muecke comment on question)

@Html.Partial() does not call a controller method - it just renders the html defined in the view named "_Partial". You need @Html.Action("_Partial", new { myNumber = 11 }) to call a server method and render the html it generates

  1. Using a ViewDataDictionary (thanks to Mark Schevchenko answer and this answer on another question)

@Html.Partial("_Partial", new { myNumber = 11 }) pass the second argument as the model, to pass parameters to controller ViewDataDictionary should be used instead

@Html.Partial("_Partial", new ViewDataDictionary { { "myNumber", 11 } }
  1. Use the integer as partial view model (thanks to Mark Schevchenko answer)

See Mark Schevchenko answer. The cons of this way is that you can't have another model on your partial view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM