我在静态枚举模型中有一组国家和国家的枚举。
public static class Enums
{
public enum Countries
{
[Display(Name = "Afghanistan")]
AFG,
[Display(Name = "United States")]
USA
}
public static class States
{
public enum USStates
{
[Display(Name = "Alabama")]
AL,
[Display(Name = "New York")]
NY
}
public enum NoStates
{
}
}
public static IEnumerable<SelectListItem> GetStatesByCountryId(int id)
{
Enums.Countries Country = (Enums.Countries)id;
switch (Country)
{
case Countries.AFG:
return null;
case Countries.USA:
return Enum.GetValues(typeof(States.USStates)).Cast<States.USStates>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
});
}
return null;
}
}
IndexModel(我的观点数据):
public class IndexModel
{
public Enums.Countries Countries { get; set; }
public Enums.States.USStates States { get; set; }
public IndexModel()
{
Countries = new Enums.Countries();
States = new Enums.States.USStates();
}
}
HomeController中:
public JsonResult GetStatesForCountry(string id)
{
if (!String.IsNullOrWhiteSpace(id))
{
int CountryId = 0;
bool Success = Int32.TryParse(id, out CountryId);
if (Success)
{
return Json(Enums.GetStatesByCountryId(CountryId), JsonRequestBehavior.AllowGet);
}
}
return null;
}
查看:
<script>
$(function () {
$('select#Countries').change(function () {
$.ajax({
type: "POST",
url: "@Url.Action("GetStatesForCountry", "Home")",
data: { id: $(this).val() },
success: function (retVal) {
$('select#States').val(retVal);
},
error: function (){
}
});
});
});
</script>
@Html.EnumDropDownListFor(m => m.Countries)
@Html.EnumDropDownListFor(m => m.States, "Please Select")
这一切看起来都很棒,令人惊讶。我刚刚把它连接起来就可以了。但是,我的模型绑定到这个USStates类型,所以我的问题是:
如何构建此类,以便此EnumDropDownList的类型不与USStates绑定?我需要的是一个对象,我可以更改它所绑定的枚举,但我不知道如何做到这一点。我可以使用ViewBag来处理数据传输,因此它不受类型约束吗?有人可以举个例子吗?我现在只开发了几个月,我非常感谢任何帮助。
在我对我的原始问题进行批量编辑和屠杀之前,这就是我所要求的。我本来希望不要依赖JQuery,但我不会想到那里。