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

asp.net-mvc – MVC2 Binding不适用于Html.DropDownListFor <

发布时间:2020-12-16 04:16:14 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试使用 Html.DropDownListFor HtmlHelper和我在帖子上绑定有点麻烦. HTML呈现正确但我在提交时从未获得“选定”值. %= Html.DropDownListFor( m = m.TimeZones,Model.TimeZones,new { @class = "SecureDropDown",name = "SelectedTimeZone" } ) % [B
我正在尝试使用 Html.DropDownListFor<> HtmlHelper和我在帖子上绑定有点麻烦. HTML呈现正确但我在提交时从未获得“选定”值.
<%= Html.DropDownListFor( m => m.TimeZones,Model.TimeZones,new { @class = "SecureDropDown",name = "SelectedTimeZone" } ) %>
[Bind(Exclude = "TimeZones")]
    public class SettingsViewModel : ProfileBaseModel
    {
        public IEnumerable TimeZones { get; set; }
        public string TimeZone { get; set; }

        public SettingsViewModel()
        {
            TimeZones = GetTimeZones();
            TimeZone = string.Empty;
        }

        private static IEnumerable GetTimeZones()
        {
            var timeZones = TimeZoneInfo.GetSystemTimeZones().ToList();
            return timeZones.Select(t => new SelectListItem 
                        { 
                            Text = t.DisplayName,Value = t.Id 
                        } );
        }
    }

我尝试了一些不同的东西,我确信我做的事情很愚蠢……只是不确定它是什么:)

解决方法

这是我为您编写的一个示例,用于说明DropDownListFor帮助方法的用法:

模型:

public class SettingsViewModel
{
    public string TimeZone { get; set; }

    public IEnumerable<SelectListItem> TimeZones 
    {
        get 
        {
            return TimeZoneInfo
                .GetSystemTimeZones()
                .Select(t => new SelectListItem 
                { 
                    Text = t.DisplayName,Value = t.Id 
                });
        }
    }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new SettingsViewModel());
    }

    [HttpPost]
    public ActionResult Index(SettingsViewModel model)
    {
        return View(model);
    }
}

视图:

<% using (Html.BeginForm()) { %>
    <%= Html.DropDownListFor(
        x => x.TimeZone,new { @class = "SecureDropDown" }
    ) %>
    <input type="submit" value="Select timezone" />
<% } %>

<div><%= Html.Encode(Model.TimeZone) %></div>

(编辑:李大同)

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

    推荐文章
      热点阅读