gpt4 book ai didi

c# - MVC Model.IsValid 用于枚举

转载 作者:太空宇宙 更新时间:2023-11-03 13:54:57 24 4
gpt4 key购买 nike

我有一个网页,其中包含一个由枚举填充的下拉列表。

public enum RegionType
{
State,
[System.Xml.Serialization.XmlEnumAttribute("County/District")]
County_District,
[System.Xml.Serialization.XmlEnumAttribute("City/Town")]
City_Town,
Municipality,
Village
}

下拉列表其实是通过下面的方式来表达枚举的:

public static List<string> GetRegionTypes()
{
List<string> theReturn = new List<string>();
theReturn.Add("");
foreach (RegionType s in Enum.GetValues(typeof(RegionType))) {
theReturn.Add(GetXmlEnumValue(s));
}
return theReturn;
}

效果很好,下拉列表显示了正确的值和所有内容。问题在于我具有“xmlenum”属性的 2 个值。如果我选择“国家/地区”或“城市/城镇”作为区域类型,则模型的“RegionType”属性无法将其转换为 MVC Controller POST 操作中的相应枚举。我如何让它正确地进行翻译?

最佳答案

您可以定义以下扩展方法,将枚举类型转换为可供 DropDownListFor 助手使用的 SelectList:

public static class EnumExtensions
{
public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
var enumType = typeof(TEnum);
if (enumType.IsGenericType && enumType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
enumType = enumType.GetGenericArguments()[0];
}

var fields = enumType.GetFields(
BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
);
var values = Enum.GetValues(enumType).OfType<TEnum>();
var items =
from value in values
from field in fields
let xmlEnumAttribute = field
.GetCustomAttributes(
typeof(XmlEnumAttribute), true
)
.OfType<XmlEnumAttribute>()
.FirstOrDefault()
let name = (xmlEnumAttribute != null)
? xmlEnumAttribute.Name
: value.ToString()
where value.ToString() == field.Name
select new { Id = value, Name = name };
return new SelectList(items, "Id", "Name", enumObj);
}
}

然后就很简单了。你有一个 View 模型:

public class MyViewModel
{
[Required]
public RegionType? Region { get; set; }
}

Controller :

public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Region = RegionType.City_Town
};
return View(model);
}

[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return Content("Thanks for choosing " + model.Region.Value.ToString());
}
}

和一个 View :

@model MyViewModel

@using (Html.BeginForm())
{
@Html.DropDownListFor(x => x.Region, Model.Region.ToSelectList(), "-- Region --")
@Html.ValidationMessageFor(x => x.Region)
<button type="submit">OK</button>
}

关于c# - MVC Model.IsValid 用于枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12537676/

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