我有一個簡單的自定義編輯器模板,用於顯示國家(國家名稱,數字ID)列表的下拉列表。我通過ViewModel1將數字ID傳遞給視圖,以便在下拉列表中選擇特定的國家/地區。即使模型包含CountryID,國家/地區ID也不會被選中。使用自定義編輯器模板時未選擇下拉列表值
使用選項3(見模板代碼),它預先選擇的國家,但MVC改變了下拉的id和名稱,例 - 如果傳遞給編輯模板(屬性名稱)的名稱爲「CountryID 「,MVC設置id =」* CountryID_CountryID *「和name =」CountryID.CountryID「。當視圖模型屬性名稱只是CountryID時,如果發佈值,那當然會搞亂綁定。
問題:我需要在自定義編輯器模板代碼中做什麼,以便在國家/地區列表下拉列表中預先選擇國家/地區?傳遞給視圖的模型包含國家的CountryID。
EDITOR模板代碼:
@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; }
}
}
COUNTRIES LIST:
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);
}
你能張貼'DLists.GetCountriesList()'和你的控制器操作的代碼? – ataravati
根據要求,我發佈了代碼,謝謝。 – Mike