Reputation: 9644
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?
Upvotes: 1
Views: 8851
Reputation: 9644
I found 3 ways thank to comments and answers:
@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
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 } }
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
Upvotes: 1
Reputation: 8197
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.
Upvotes: 3