我有一个用于下拉列表的简单自定义编辑器模板,其中显示了国家列表(国家名称、数字 ID)。我通过 ViewModel1 将数字 ID 传递给视图,以便已在下拉列表中选择了特定国家/地区。即使模型包含 CountryID,也不会选择国家 ID。
使用选项 3(参见模板代码)它确实预先选择了国家,但 MVC 更改了下拉列表的 id 和名称,例如 - 如果传递给编辑器模板的名称(属性名称)是“ CountryID ”,MVC 设置 id= “*CountryID_CountryID*”和名称=“ CountryID.CountryID ”。当然,当在 View Model 属性名称中发布的值只是 CountryID 时,这会打乱绑定。
问题:我需要在自定义编辑器模板代码中做什么,以便在国家列表下拉列表中预先选择国家?传递给视图的模型包含国家的 CountryID。
编辑器模板代码:
@model short
@using PSP.Lib;
@{
SelectList TheSelectList = null;
string FieldName = ViewData.ModelMetadata.PropertyName; //FieldName only used when I tried the commented out option.
TheSelectList = DLists.GetCountriesList(); //just gets list of countries and a numeric id for each.
}
<div class="editor-label">
@Html.LabelFor(model => model)
</div>
<div class="editor-field">
@Html.DropDownList("", TheSelectList) //==1. country id passed thru model does not get selected on list.
@* @Html.DropDownListFor(model => model, TheSelectList) *@ //==2. as above, does not work.
@* @Html.DropDownList(FieldName, TheSelectList) *@ //==3. country id passed thru model DOES get selected BUT, id and name parameters get changed.
</div>
视图: 仅显示相关代码
@model PSP.ViewModels.ViewModel1
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>EventList</legend>
@Html.EditorFor(model => model.CountryID)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
VIEWMODEL1: 仅显示相关代码
namespace PSP.ViewModels
{
public class ViewModel1
{
public short CountryID { get; set; }
}
}
国家名单:
public static SelectList GetCountriesList()
{
AccDBEntities db = new AccDBEntities();
var ls = (from ct in db.Countries
select new { Text = ct.NameText, Value = ct.ID, Selected = false }).ToList();
return new SelectList(ls, "Value", "Text");
}
控制器: 仅显示相关代码
public ActionResult Create()
{
ViewModel1 VM1 = new ViewModel1();
VM1.CountryID = 50; //just pre-selecting a country id in the dropdown list
return View(VM1);
}