Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Wednesday, September 7, 2016 4:33 PM
Hello,
I have a Partial view in my ASP.NET MVC project. In one of my Razor views, I want to use the partial in multiple spots. The general idea is to have something like this:
<div id="parent1">
@Html.Partial("_MyPartial.cshtml", new { parent="parent1", value=1.23 })
</div>
<div id="anotherDivId">
@Html.Partial("_MyPartial.cshtml", new { parent="anotherDivId", value=3.21 })
</div>
<div id="something123">
@Html.Partial("_MyPartial.cshtml", new { parent="something123", value=5.79 })
</div>
Then _MyPartial.cshtml looks roughly like this:
@model ?
<div data-parent="@Model.parent" onclick="executeThis();">
...
</div>
I don't know what the Model type should be in _MyPartial.cshtml. In short, how can I pass some hard-coded data from my Razor view to my partial? Do I really have to create another model class to make this happen? I just want to quickly pass some key/value pairs from the Razor view to the partial.
All replies (4)
Wednesday, September 7, 2016 5:57 PM ✅Answered
Partial view can take model same like a normal view
Create a new partial model inside model folder
public class PartialModel
{
public string Parent { get; set; }
public decimal Value { get; set; }
}
Create a partial View _CustomPartialView.cshtml
@model YourProject.Web.Models.PartialModel
<div data-parent="@Model.Parent" data-value="@Model.Value" onclick="executeThis();">
</div>
and add that to your normal/another partial view like following
<div id="parent1">
@Html.Partial("_CustomPartialView", new PartialModel { Parent = "parent1", Value = 2.03M })
</div>
<div id="parent2">
@Html.Partial("_CustomPartialView", new PartialModel { Parent = "parent2", Value = 9.03M })
</div>
Let me know if you still have any confusion
Thursday, September 8, 2016 10:00 AM ✅Answered
Hi A.paranoid.android,
If you do not want to add another model, you could use ViewDataDictionary.
<div id="parent1">
@Html.Partial("_MyPartial", new ViewDataDictionary { { "parent", "parent1" }, { "value", 1.23 } })
</div>
<div id="anotherDivId">
@Html.Partial("_MyPartial", new ViewDataDictionary { { "parent", "anotherDivId" }, { "value", 3.21 } })
</div>
<div id="something123">
@Html.Partial("_MyPartial", new ViewDataDictionary { { "parent", "something123" }, { "value", 5.79 } })
</div>
_MyPartial
<div>
parent: @ViewData["parent"]
<br />
value: @ViewData["value"]
</div>
Best Regards,
Chris
Wednesday, September 7, 2016 5:37 PM
See at this link:
http://stackoverflow.com/questions/20799658/how-can-i-pass-parameters-to-a-partial-view-in-mvc-4
Hope it helps.
Rgds
Krzysztof
Thursday, September 8, 2016 12:32 PM
http://gyansangrah.com/gyansangrah/article/passing_parameter_partial_views_asp_net_mvc