【发布时间】:2013-10-19 04:32:05
【问题描述】:
我有以下用于模型的类:
public class ApplicationUser
{
public int? UserId { get; set; }
public TimeZoneInfo TimeZoneDefault { get; set; }
public string Username { get; set; }
[...]
}
在视图中,我有以下代码成功创建了下拉列表:
@model Acme.ApplicationUser
@{
var timeZoneList = TimeZoneInfo
.GetSystemTimeZones()
.Select(t => new SelectListItem
{
Text = t.DisplayName,
Value = t.Id,
Selected = Model != null && t.Id == Model.TimeZoneDefault.Id
});
}
在表单中调用它:
<table>
[....]
<tr>
<td>
@Html.LabelFor(model => model.TimeZoneDefault, "Default Time Zone:")</strong> </td>
<td>
@Html.DropDownListFor(model => model.TimeZoneDefault, timeZoneList)
<input type="submit" value="Save" />
</td>
</tr>
</table>
一切都显示正确,问题又出在控制器上,我有这个:
[HttpPost]
public ActionResult Profile(ApplicationUser model)
{
if (ModelState.IsValid)
{
model.Save();
}
return View();
}
回传时ModelState无效,错误为:
System.InvalidOperationException: 参数从类型转换 'System.String' 键入 'System.TimeZoneInfo' 失败,因为没有类型 转换器可以在这些类型之间进行转换。
我需要做什么才能将所选值转换回 TimeZoneInfo?
【问题讨论】:
-
您可能需要编写自己的自定义模型绑定器。我从一个快速的谷歌上找到了这个:shopmvc.com/news/8/…
标签: c# asp.net-mvc