如何使用标志枚举时减少ASP.NET MVC视图代码重复 [英] How to reduce code duplication in ASP.NET MVC view when working with Flags enum

查看:226
本文介绍了如何使用标志枚举时减少ASP.NET MVC视图代码重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原谅我的无知。不是做了很多MVC的工作,我敢肯定,必须有一个更好的办法做到这一点,但我似乎无法找到它。我有一个标志枚举是这样的:

Forgive my ignorance. Not done a lot of MVC work, and I'm sure there must be a better way to do this but I can't seem to find it. I have a Flags enum like this:

[Flags]
public enum Services
{
    Foo = 1,
    Bar = 2,
    Meh = 4
}

和具有这种类型的值在我的模型一个SelectedServices属性。在视图中,我为每个可能的服务的复选框。我已经实现了绑定逻辑,像这样:

And a SelectedServices property on my Model which has a value of this type. In the View, I have a checkbox for each possible service. I have implemented the binding logic like so:

<div><label><input type="checkbox" name="services" value="@((int)Services.Foo)" 
@if(Model.SelectedServices.HasFlag(Services.Foo))
{
    <text>checked</text>
}
 />Foo</label></div>

<div><label><input type="checkbox" name="services" value="@((int)Services.Bar)" 
@if(Model.SelectedServices.HasFlag(Services.Bar))
{
    <text>checked</text>
}
 />Bar</label></div>



等。它的工作原理,但确实是可怕的混乱。

And so on. Which works, but is really horribly messy.

有一定,肯定有更好的方式来封装 - 但我不知道相关的概念是MVC

There must, surely be a better way to encapsulate this - but I have no idea what the relevant concept is in MVC?

推荐答案

创建剃刀帮手:

@helper DisplayFlagHelper(Services flag)
{
   <div><label><input type="checkbox" name="services" value="@((int)flag)" 
   if(Model.SelectedServices.HasFlag(flag))
   {
       <text>checked</text>
   }
    />@flag</label></div>
}



@DisplayFlagHelper(Services.Foo)

@DisplayFlagHelper(Services.Foo)

或共享视图

这篇关于如何使用标志枚举时减少ASP.NET MVC视图代码重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆