Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在MVC中绑定TimeZoneInfo_C#_Asp.net Mvc - Fatal编程技术网

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)