c# - 如何在 MVC 中绑定(bind) TimeZoneInfo

标签 c# asp.net-mvc

我有以下用于模型的类:

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/

相关文章:

c# - Mysql - "order by"/Subquery 上的 Entity Framework 性能问题

c# - MVC 5 本地化工作在 localhost 但不是服务器

c# - DataTypeAttribute 验证是否在 MVC2 中工作?

c# - 从 MVC 中的部分 View 加载菜单

c# - 模型和 Controller 之间的关注点分离

asp.net-mvc - ASP.NET MVC 3 Razor 智能感知

c# - 正则表达式查找 Href 值

c# - 将多行字符串变量从 C# 传递到 javascript

c# - MVC 5.2.3 - 全局化 - 日期时间到带范围的十进制

c# - 转换分割字符串时出错