C# 如何在MVC中绑定TimeZoneInfo
我有以下用于模型的类:C# 如何在MVC中绑定TimeZoneInfo,c#,asp.net-mvc,C#,Asp.net Mvc,我有以下用于模型的类: public class ApplicationUser { public int? UserId { get; set; } public TimeZoneInfo TimeZoneDefault { get; set; } public string Username { get; set; } [...] } 在视图中,我有以下成功创建下拉列表的代码: @model Acme.ApplicationUser @{ var
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>
发回时ModelState无效,错误为:
System.InvalidOperationException:类型的参数转换
“System.String”无法键入“System.TimeZoneInfo”,因为没有类型
转换器可以在这些类型之间进行转换
要将所选值转换回时区信息,我需要做什么?如果不想使用自定义活页夹,可以使用以下技巧:
// Model
public class test
{
public string TimeZoneId { get; set; }
public TimeZoneInfo TimeZone
{
get { return TimeZoneInfo.FindSystemTimeZoneById(TimeZoneId); }
set { TimeZoneId = value.Id; }
}
}
并在您的视图中绑定到时区ID
:
@Html.DropDownListFor(m => m.TimeZoneId, timeZoneList)
您可能需要编写自己的自定义模型活页夹。我在一个快速的谷歌上找到了这个:
@Html.DropDownListFor(m => m.TimeZoneId, timeZoneList)