我有以下用于模型的类:
public class ApplicationUser
{
public int? UserId { get; set; }
public TimeZoneInfo TimeZoneDefault { get; set; }
public string Username { get; set; }
[...]
}
在 View 中,我有以下成功创建下拉列表的代码:
@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>
一切都显示正确,问题又出现在 Controller 上,我有这个:
[HttpPost]
public ActionResult Profile(ApplicationUser model)
{
if (ModelState.IsValid)
{
model.Save();
}
return View();
}
回传时ModelState无效,错误为:
System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.TimeZoneInfo' failed because no type converter can convert between these types.
我需要做什么才能将所选值转换回 TimeZoneInfo?
最佳答案
如果你不想使用自定义 Binder ,你可以使用这个技巧:
// Model
public class test
{
public string TimeZoneId { get; set; }
public TimeZoneInfo TimeZone
{
get { return TimeZoneInfo.FindSystemTimeZoneById(TimeZoneId); }
set { TimeZoneId = value.Id; }
}
}
并在您的 View 中绑定(bind)到 TimeZoneId
:
@Html.DropDownListFor(m => m.TimeZoneId, timeZoneList)
关于c# - 如何在 MVC 中绑定(bind) TimeZoneInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19457400/