Rik*_*kon 33 c# asp.net-mvc model-binding enum-flags asp.net-mvc-3
我有一个Enum Flags网格,其中每个记录都是一行复选框,用于确定记录的标志值.这是系统提供的通知列表,用户可以选择(每个)他们希望如何传递的通知:
[Flag]
public enum NotificationDeliveryType
{
InSystem = 1,
Email = 2,
Text = 4
}
Run Code Online (Sandbox Code Playgroud)
我找到了这篇文章,但他正在取回一个标志值,并且他将它绑定在控制器中,就像这样(一周中的几天概念):
[HttpPost]
public ActionResult MyPostedPage(MyModel model)
{
//I moved the logic for setting this into a helper
//because this could be re-used elsewhere.
model.WeekDays = Enum<DayOfWeek>.ParseToEnumFlag(Request.Form, "WeekDays[]");
...
}
Run Code Online (Sandbox Code Playgroud)
我无法找到MVC 3模型绑定器可以处理标志的任何地方.谢谢!
Dar*_*rov 71
一般来说,我在设计视图模型时避免使用枚举,因为它们不能与ASP.NET MVC的助手和开箱即用的模型绑定器一起使用.它们在您的域模型中非常精细,但对于视图模型,您可以使用其他类型.所以我留下了我的映射层,它负责在我的域模型和视图模型之间来回转换,以担心这些转换.
这就是说,如果出于某种原因你决定在这种情况下使用枚举,你可以滚动自定义模型绑定器:
public class NotificationDeliveryTypeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value != null )
{
var rawValues = value.RawValue as string[];
if (rawValues != null)
{
NotificationDeliveryType result;
if (Enum.TryParse<NotificationDeliveryType>(string.Join(",", rawValues), out result))
{
return result;
}
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Run Code Online (Sandbox Code Playgroud)
将在Application_Start中注册:
ModelBinders.Binders.Add(
typeof(NotificationDeliveryType),
new NotificationDeliveryTypeModelBinder()
);
Run Code Online (Sandbox Code Playgroud)
到现在为止还挺好.现在标准的东西:
查看型号:
[Flags]
public enum NotificationDeliveryType
{
InSystem = 1,
Email = 2,
Text = 4
}
public class MyViewModel
{
public IEnumerable<NotificationDeliveryType> Notifications { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Notifications = new[]
{
NotificationDeliveryType.Email,
NotificationDeliveryType.InSystem | NotificationDeliveryType.Text
}
};
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
Run Code Online (Sandbox Code Playgroud)
查看(~/Views/Home/Index.cshtml
):
@model MyViewModel
@using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th>Notification</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(x => x.Notifications)
</tbody>
</table>
<button type="submit">OK</button>
}
Run Code Online (Sandbox Code Playgroud)
NotificationDeliveryType
(~/Views/Shared/EditorTemplates/NotificationDeliveryType.cshtml
)的自定义编辑器模板:
@model NotificationDeliveryType
<tr>
<td>
@foreach (NotificationDeliveryType item in Enum.GetValues(typeof(NotificationDeliveryType)))
{
<label for="@ViewData.TemplateInfo.GetFullHtmlFieldId(item.ToString())">@item</label>
<input type="checkbox" id="@ViewData.TemplateInfo.GetFullHtmlFieldId(item.ToString())" name="@(ViewData.TemplateInfo.GetFullHtmlFieldName(""))" value="@item" @Html.Raw((Model & item) == item ? "checked=\"checked\"" : "") />
}
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
很明显,软件开发人员(在本例中为我)在编辑器模板中编写这样的代码不应该为他的工作感到自豪.我的意思是看!即使我在5分钟前写过这个Razor模板,也无法理解它的作用.
因此,我们在可重用的自定义HTML帮助器中重构此意大利面条代码:
public static class HtmlExtensions
{
public static IHtmlString CheckBoxesForEnumModel<TModel>(this HtmlHelper<TModel> htmlHelper)
{
if (!typeof(TModel).IsEnum)
{
throw new ArgumentException("this helper can only be used with enums");
}
var sb = new StringBuilder();
foreach (Enum item in Enum.GetValues(typeof(TModel)))
{
var ti = htmlHelper.ViewData.TemplateInfo;
var id = ti.GetFullHtmlFieldId(item.ToString());
var name = ti.GetFullHtmlFieldName(string.Empty);
var label = new TagBuilder("label");
label.Attributes["for"] = id;
label.SetInnerText(item.ToString());
sb.AppendLine(label.ToString());
var checkbox = new TagBuilder("input");
checkbox.Attributes["id"] = id;
checkbox.Attributes["name"] = name;
checkbox.Attributes["type"] = "checkbox";
checkbox.Attributes["value"] = item.ToString();
var model = htmlHelper.ViewData.Model as Enum;
if (model.HasFlag(item))
{
checkbox.Attributes["checked"] = "checked";
}
sb.AppendLine(checkbox.ToString());
}
return new HtmlString(sb.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
我们清理编辑器模板中的混乱:
@model NotificationDeliveryType
<tr>
<td>
@Html.CheckBoxesForEnumModel()
</td>
</tr>
Run Code Online (Sandbox Code Playgroud)
产生表:
现在很明显,如果我们能够为这些复选框提供更友好的标签,那就太好了.例如:
[Flags]
public enum NotificationDeliveryType
{
[Display(Name = "in da system")]
InSystem = 1,
[Display(Name = "@")]
Email = 2,
[Display(Name = "txt")]
Text = 4
}
Run Code Online (Sandbox Code Playgroud)
我们所要做的就是调整我们之前编写的HTML帮助器:
var field = item.GetType().GetField(item.ToString());
var display = field
.GetCustomAttributes(typeof(DisplayAttribute), true)
.FirstOrDefault() as DisplayAttribute;
if (display != null)
{
label.SetInnerText(display.Name);
}
else
{
label.SetInnerText(item.ToString());
}
Run Code Online (Sandbox Code Playgroud)
这给了我们更好的结果:
Bit*_*ped 14
Darin的代码很棒,但我在使用MVC4时遇到了一些麻烦.
在创建框的HtmlHelper扩展中,我不断得到模型不是枚举的运行时错误(具体来说,说System.Object).我重新编写代码以获取Lambda表达式并使用ModelMetadata类清除此问题:
public static IHtmlString CheckBoxesForEnumFlagsFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumModelType = metadata.ModelType;
// Check to make sure this is an enum.
if (!enumModelType.IsEnum)
{
throw new ArgumentException("This helper can only be used with enums. Type used was: " + enumModelType.FullName.ToString() + ".");
}
// Create string for Element.
var sb = new StringBuilder();
foreach (Enum item in Enum.GetValues(enumModelType))
{
if (Convert.ToInt32(item) != 0)
{
var ti = htmlHelper.ViewData.TemplateInfo;
var id = ti.GetFullHtmlFieldId(item.ToString());
var name = ti.GetFullHtmlFieldName(string.Empty);
var label = new TagBuilder("label");
label.Attributes["for"] = id;
var field = item.GetType().GetField(item.ToString());
// Add checkbox.
var checkbox = new TagBuilder("input");
checkbox.Attributes["id"] = id;
checkbox.Attributes["name"] = name;
checkbox.Attributes["type"] = "checkbox";
checkbox.Attributes["value"] = item.ToString();
var model = htmlHelper.ViewData.Model as Enum;
if (model.HasFlag(item))
{
checkbox.Attributes["checked"] = "checked";
}
sb.AppendLine(checkbox.ToString());
// Check to see if DisplayName attribute has been set for item.
var displayName = field.GetCustomAttributes(typeof(DisplayNameAttribute), true)
.FirstOrDefault() as DisplayNameAttribute;
if (displayName != null)
{
// Display name specified. Use it.
label.SetInnerText(displayName.DisplayName);
}
else
{
// Check to see if Display attribute has been set for item.
var display = field.GetCustomAttributes(typeof(DisplayAttribute), true)
.FirstOrDefault() as DisplayAttribute;
if (display != null)
{
label.SetInnerText(display.Name);
}
else
{
label.SetInnerText(item.ToString());
}
}
sb.AppendLine(label.ToString());
// Add line break.
sb.AppendLine("<br />");
}
}
return new HtmlString(sb.ToString());
}
Run Code Online (Sandbox Code Playgroud)
我还扩展了模型绑定器,因此它适用于任何通用枚举类型.
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
// Fetch value to bind.
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (value != null)
{
// Get type of value.
Type valueType = bindingContext.ModelType;
var rawValues = value.RawValue as string[];
if (rawValues != null)
{
// Create instance of result object.
var result = (Enum)Activator.CreateInstance(valueType);
try
{
// Parse.
result = (Enum)Enum.Parse(valueType, string.Join(",", rawValues));
return result;
}
catch
{
return base.BindModel(controllerContext, bindingContext);
}
}
}
return base.BindModel(controllerContext, bindingContext);
}
Run Code Online (Sandbox Code Playgroud)
您仍然需要在Application_Start中注册每个枚举类型,但至少这样就不需要单独的绑定器类.您可以使用以下方式注册:
ModelBinders.Binders.Add(typeof(MyEnumType), new EnumFlagsModelBinder());
Run Code Online (Sandbox Code Playgroud)
我在Github上发布了我的代码:https://github.com/Bitmapped/MvcEnumFlags.
您可以尝试MVC Enum Flags包(可通过nuget获得).它会自动跳过零值枚举选项,这是一个不错的选择.
[以下内容来自文件及其评论; 如果这不适合你,请看那里]
安装后,将以下内容添加到Global.asax.cs\Application_Start:
ModelBinders.Binders.Add(typeof(MyEnumType), new EnumFlagsModelBinder());
然后在视图中,@using MvcEnumFlags
顶部和@Html.CheckBoxesForEnumFlagsFor(model => model.MyEnumTypeProperty)
实际代码.
归档时间: |
|
查看次数: |
21743 次 |
最近记录: |