emr*_*azi 5 c# asp.net asp.net-mvc razor asp.net-mvc-4
我发现了几个关于我的问题的问题,但没有一个问题实际上解决了问题,并提出了问题的替代解决方案,这就是为什么我再次问这个问题.
我使用的是强类型HTML帮助程序,而不是仅用于页面标题的ViewData和ViewBag.
这是我的问题.
我有以下viewmodel.
public class RegisterViewModel
{
public string Mail { get; set; }
public string Name { get; set; }
public ThreePartDatePickerViewModel ThreePartDateSelection { get; set; }
public RegisterViewModel()
{
ThreePartDateSelection = new ThreePartDatePickerViewModel();
}
}
Run Code Online (Sandbox Code Playgroud)
以上viewmodel使用下面的viewmodel,它基本上保存3个下拉列表的数据,即日,月和年.
public class ThreePartDatePickerViewModel
{
public string Day { get; set; }
public string Year { get; set; }
public string Month { get; set; }
public IList<SelectListItem> Years { get; set; }
public IList<SelectListItem> Months { get; set; }
public IList<SelectListItem> Days { get; set; }
public ThreePartDatePickerViewModel()
{
var now = DateTime.Now;
Years = new List<SelectListItem>();
Months = new List<SelectListItem>();
Days = new List<SelectListItem>();
var empty = new SelectListItem { Text = "" };
Years.Add(empty);
Months.Add(empty);
Days.Add(empty);
foreach(var item in Enumerable.Range(0, 100).Select(x => new SelectListItem { Value = (now.Year - x).ToString(), Text = (now.Year - x).ToString() }))
Years.Add(item);
foreach(var item in Enumerable.Range(1, 12).Select(x => new SelectListItem { Value = x.ToString(), Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x) }))
Months.Add(item);
foreach(var item in Enumerable.Range(1, 31).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() }))
Days.Add(item);
}
}
Run Code Online (Sandbox Code Playgroud)
在返回RegisterViewModel
查看的操作方法中,我设置了Day,Month和Year属性ThreePartDatePickerViewModel
.
我在运行时检查了这些值,同时生成视图并且它们是正确的.
在我的主要观点中,
@model Bla.Bla.RegisterViewModel
<!-- Helpers for other properties -->
@Html.EditorFor(m => m.ThreePartDateSelection)
Run Code Online (Sandbox Code Playgroud)
我的ThreePartDatePickerViewModel编辑器模板是
@model Bla.Bla.ThreePartDatePickerViewModel
<div class="threePartDatePicker">
@Html.DropDownListFor(m => m.Day, Model.Days)
@Html.DropDownListFor(m => m.Month, Model.Months)
@Html.DropDownListFor(m => m.Year, Model.Years)
</div>
Run Code Online (Sandbox Code Playgroud)
在我最终渲染的html中,我按预期拥有所有控件.下拉列表正常,但未选中我在操作方法中设置的值.
如果我从EditorTemplates切换到部分视图,它开始工作.或者,如果直接在主视图中呈现下拉列表,而不是将模型传递给EditorFor,它再次起作用.
看来是老bug了,还没解决。据报道。
我必须编辑编辑器模板以将所选值设置为,
@{
//capture the selected list wherever it is. Here it passed in additionalViewData
SelectList tmpList, list = null;
ViewContext.ViewData.TryGetValue("list", out tmpList);
if (tmpList != null && tmpList.Count() > 0 && tmpList.SelectedValue == null)
{
list = new SelectList(tmpList, "Value", "Text", Model);
}
else
{
list = tmpList;
}
}
<div class="form-group">
@Html.DropDownListFor(m => m, list, attributes)
</div>
Run Code Online (Sandbox Code Playgroud)
所以我可以使用编辑器模板中的选择列表作为默认行为。
归档时间: |
|
查看次数: |
1285 次 |
最近记录: |