我想将数据从控制器传递到视图。在我的晚餐控制中,我有一个编辑动作。代码是
//
// GET: /Dinner/Edit/5
public ActionResult Edit(int id)
{
var dinner = _repository.GetDinner(id);
ViewData["Countries"] = new SelectList(PhoneValidator.AllCountries, dinner.Country);
return View(dinner);
}
然后,我想使用下拉列表在编辑视图页面中显示国家/地区的信息。我的代码是
<div class="editor-label">
@Html.EditorFor(model => model.Country)
</div>
<div class="editor-field">
@Html.DropDownList("Country", ViewData["Countries"] as SelectList)
@Html.ValidationMessageFor(model => model.Country)
</div>
然后,我在这一行中收到错误
@Html.DropDownList("Country", ViewData["Countries"] as SelectList)
错误信息是
The ViewData item that has the key 'Country' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'
注意:
我有一个班级名字DinnerViolation,我这个班,我有一个得到 检索我在编辑控制器中使用的所有条件的方法来设置SelectList的值,请检查代码:
public class PhoneValidator
{
static IDictionary<string, Regex> countryRegex = new Dictionary<string, Regex>() {
{ "USA", new Regex("^[2-9]\\d{2}-\\d{3}-\\d{4}$")},
{ "UK", new Regex("(^1300\\d{6}$)|(^1800|1900|1902\\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\\d{4}$)|(^04\\d{2,3}\\d{6}$)")},
{ "Netherlands", new Regex("(^\\+[0-9]{2}|^\\+[0-9]{2}\\(0\\)|^\\(\\+[0-9]{2}\\)\\(0\\)|^00[0-9]{2}|^0)([0-9]{9}$|[0-9\\-\\s]{10}$)")},
};
public static bool IsValidNumber(string phoneNumber, string country)
{
if (country != null && countryRegex.ContainsKey(country))
return countryRegex[country].IsMatch(phoneNumber);
else
return false;
}
public static IEnumerable<string> AllCountries
{
get
{
return countryRegex.Keys;
}
}
}
}
有什么帮助吗?谢谢
答案 0 :(得分:0)
您将返回IEnumerable<string>
public static IEnumerable<string> AllCountries
{
get
{
return countryRegex.Keys;
}
}
当您需要返回IEnumerable<SelectListItem>
像这样(未经测试):
public static IEnumerable<SelectListItem> AllCountries
{
get
{
var countries = new List<SelectListItem>();
foreach(var country in countryRegex.Keys)
{
countries.Add(SelectListItem() { Text = country, Value = country };
}
return countries;
}
}