加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何在MVC中绑定TimeZoneInfo

发布时间:2020-12-16 01:57:51 所属栏目:百科 来源:网络整理
导读:我有以下类用于模型: public class ApplicationUser{ public int? UserId { get; set; } public TimeZoneInfo TimeZoneDefault { get; set; } public string Username { get; set; } [...]} 在视图中,我有以下代码成功创建下拉列表: @model Acme.Applicati
我有以下类用于模型:

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: The parameter conversion from type
‘System.String’ to type ‘System.TimeZoneInfo’ failed because no type
converter can convert between these types.

如何将选定的值转换回TimeZoneInfo,我需要做什么?

解决方法

如果您不想使用自定义绑定器,可以使用此技巧:

// 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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读