【问题标题】:How to Bind TimeZoneInfo in MVC如何在 MVC 中绑定 TimeZoneInfo
【发布时间】: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


【解决方案1】:

如果你不想使用自定义活页夹,你可以使用这个技巧:

// Model
public class test
{
    public string TimeZoneId { get; set; }
    public TimeZoneInfo TimeZone 
    { 
        get { return TimeZoneInfo.FindSystemTimeZoneById(TimeZoneId); }
        set { TimeZoneId = value.Id; } 
    }
}

在你看来绑定到TimeZoneId:

@Html.DropDownListFor(m => m.TimeZoneId, timeZoneList)

【讨论】:

    猜你喜欢
    • 2012-09-14
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多