简体   繁体   English

相同视图的ASP.NET MVC部分视图

[英]ASP.NET MVC Partial Views for Identical Views

I have two controllers in my MVC project, each having a Weapon action/view. 我的MVC项目中有两个控制器,每个控制器都有一个Weapon操作/视图。 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 . 这两个视图的@model属性都设置为WeaponViewModel ,根据视图的不同,例如,一个视图ViewModel.Weapon = Axe和另一视图ViewModel.Weapon = Sword Axe and Sword implement an IWeapon interface so have identical properties. AxeSword实现IWeapon接口,因此具有相同的属性。

Since each view renders the same WeaponViewModel , i find it an overkill to have identical Razor code for two views. 由于每个视图都呈现相同的WeaponViewModel ,所以我发现两个视图具有相同的Razor代码是一个过大的选择。 What I did was to create a View named _Weapon in the Shared folder as such: _Weapon是在Shared文件夹中创建一个名为_Weapon的视图,如下所示:

@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? 结果有效,但是我的问题是:使用Html.RenderPartial渲染(本质上)完整视图是否正确? 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? 另外,如果以后我决定更细化并在共享的_Weapon视图中创建其他局部视图,是否有需要注意的地方?

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
    { //...}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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