【发布时间】:2013-06-05 18:37:41
【问题描述】:
我想将数据从控制器传递到视图。在我的晚餐控件中,我有一个编辑操作。代码是
//
// 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>'
注意:
- 我的餐桌上有一个“Country”属性。国家的类型是字符串。
- 我认为错误行中的“国家”只是在 该字段的形式。所以这个错误似乎是不合理的。
-
我有一个类名DinnerViolation,我这个类,我有一个get 检索我在编辑控制器中用于设置 SelectList 值的 allcontries 的方法,请检查代码:
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; } } }}
有什么帮助吗?谢谢
【问题讨论】:
-
开始使用 ViewModel 并停止使用
ViewData和ViewBag。