gpt4 book ai didi

c# - 枚举标志的模型绑定(bind)列表

转载 作者:IT王子 更新时间:2023-10-29 04:07:08 24 4
gpt4 key购买 nike

我有一个枚举标志网格,其中每条记录都是一行复选框,用于确定该记录的标志值。这是系统提供的通知列表,用户可以选择(为每个通知)他们希望如何发送:

[Flag]
public enum NotificationDeliveryType
{
InSystem = 1,
Email = 2,
Text = 4
}

我找到了这个 article但是他返回了一个标志值,并且像这样将其绑定(bind)到 Controller 中(使用星期几的概念):

[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[]");
...
}

我找不到 MVC 3 模型联编程序可以处理标志的任何地方。谢谢!

最佳答案

一般来说,我在设计我的 View 模型时避免使用枚举,因为它们不使用 ASP.NET MVC 的助手和开箱即用的模型绑定(bind)器。它们在您的域模型中非常好,但对于 View 模型,您可以使用其他类型。因此,我让负责在领域模型和 View 模型之间来回转换的映射层来处理这些转换。

也就是说,如果出于某种原因您决定在这种情况下使用枚举,您可以推出自定义模型绑定(bind)器:

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);
}
}

将在Application_Start中注册:

ModelBinders.Binders.Add(
typeof(NotificationDeliveryType),
new NotificationDeliveryTypeModelBinder()
);

到目前为止一切顺利。现在是标准的东西:

查看模型:

[Flags]
public enum NotificationDeliveryType
{
InSystem = 1,
Email = 2,
Text = 4
}

public class MyViewModel
{
public IEnumerable<NotificationDeliveryType> Notifications { get; set; }
}

Controller :

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);
}
}

View (~/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>
}

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>

很明显,在编辑器模板中编写此类代码的软件开发人员(在本例中为我)不应该为自己的工作感到骄傲。我的意思是看它!即使是 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());
}
}

然后我们清理编辑器模板中的困惑:

@model NotificationDeliveryType
<tr>
<td>
@Html.CheckBoxesForEnumModel()
</td>
</tr>

生成表格:

enter image description here

显然,如果我们能为这些复选框提供更友好的标签,那就太好了。例如:

[Flags]
public enum NotificationDeliveryType
{
[Display(Name = "in da system")]
InSystem = 1,

[Display(Name = "@")]
Email = 2,

[Display(Name = "txt")]
Text = 4
}

我们所要做的就是调整我们之前编写的 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());
}

这给了我们更好的结果:

enter image description here

关于c# - 枚举标志的模型绑定(bind)列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9264927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com