我有4个下拉菜单,插入工作正常,如何编辑数据并将数据保存到db mvc2。我在更新时遇到错误 - 具有键'SelectedTimeZone'的ViewData项的类型为'System.String'但必须是'IEnumerable
类型My Controller
public ActionResult Edit(int id)
{
return View(EventModel.Edit(id));
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Edit(int id, EventInfo EventInfo)
{
if (ModelState.IsValid)
{
EventModel.Edit(EventInfo);
return RedirectToAction("Index");
}
return View(EventInfo);
}
Model
public SelectList TimeZones { get; set; }
public SelectList EventType { get; set; }
private string selectedTimeZone = "";
public string SelectedTimeZone
{
get { return selectedTimeZone; }
set { selectedTimeZone = value; }
}
Load Function
myEventInfo.TimeZones = new SelectList(EventModel.getTIMEZOMES, "Key", "Value");
myEventInfo.SelectedTimeZone = Datareader["TIMEZONE"].ToString();
public static IList<KeyValuePair<string, string>> getTIMEZOMES
{
get
{
Dbhelper DbHelper = new Dbhelper();
IList<KeyValuePair<String, String>> Timezone = new List<KeyValuePair<String, String>>();
DbCommand cmd = DbHelper.GetSqlStringCommond("SELECT * FROM TMP_TIMEZONES");
DbDataReader Datareader = DbHelper.ExecuteReader(cmd);
while (Datareader.Read())
{
Timezone.Add(new KeyValuePair<String, String>(Datareader["ABBR"].ToString(), Datareader["NAME"].ToString()));
}
return Timezone;
}
}
View page
<%= Html.DropDownListFor(model => model.SelectedTimeZone, Model.TimeZones, "Select Timezone", new { style = "width:200px", @class = "textfield165" })%>
<%= Html.ValidationMessageFor(model => model.SelectedTimeZone)%>
我在更新时遇到错误/具有键'SelectedTimeZone'的ViewData项的类型为'System.String',但必须是'IEnumerable
类型答案 0 :(得分:1)
在您的POST操作中,如果出现错误,您忘记填充TimeZones
属性。不要忘记只有选定的时区是POSTed,而不是时区列表,所以如果您打算重新显示相同的视图(例如出现错误),请确保重新绑定此列表(与绑定它的方式相同)在允许您在第一个位置显示表单的GET操作中:
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Edit(int id, EventInfo EventInfo)
{
if (ModelState.IsValid)
{
EventModel.Edit(EventInfo);
return RedirectToAction("Index");
}
// Here you must populate the TimeZones property before returning the view
EventInfo.TimeZones = new SelectList(EventModel.getTIMEZOMES, "Key", "Value");
return View(EventInfo);
}