简体   繁体   中英

ASP.NET MVC Partial Views for Identical Views

I have two controllers in my MVC project, each having a Weapon action/view. Both views have their @model property set to a WeaponViewModel with different properties depending on the view, eg for one view, ViewModel.Weapon = Axe and for the other view ViewModel.Weapon = Sword . Axe and Sword implement an IWeapon interface so have identical properties.

Since each view renders the same WeaponViewModel , i find it an overkill to have identical Razor code for two views. What I did was to create a View named _Weapon in the Shared folder as such:

@model WeaponViewModel
//razor code goes here

..and in the two views I now only have this code:

@model WeaponViewModel
@{ Html.RenderPartial("_Weapon", Model); }

The result works but my question is: is it correct to use Html.RenderPartial to render (essentially) a complete view? Also, If I later decide to become more granular and create additional partial views in my shared _Weapon view, are there any gotchas to look out for?

Without fully understanding your project, it sounds more like a design aspect rather than a technical issue.
For this specific case, you might want to consider moving all the shared logic from each "weapon" to a single controller that will handle all weapons.
this controller will be responsible for all the partial views of all current and future weapons,
while the main view will call the relevant partial view depending on the weapon type.
Something like:

Html.RenderPartial("~/Views/Weapon/" + Model.Type, Model);

while in the weapon controller you'll have :

public class WeaponController : Controller
{
    public ActionResult Axe
    { //...}

    public ActionResult Sword
    { //...}
}

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