我在編輯器模板中有一個Html.DropDownListFor,它可以設置一個選定的值。 如果我用部分視圖替換編輯器模板(將編輯器模板中的HTML複製粘貼到部分視圖中),它將起作用。Html.DropDownListFor在編輯器模板中未設置選定值
示例代碼
型號:
public class MainItemViewModel
{
public int MainItemId { get; set; }
public ItemViewModel ItemViewModel { get; set; }
}
public class ItemViewModel
{
public int ItemId { get; set; }
public string Text { get; set; }
public IEnumerable<SelectListItem> ItemSelectList { get; set; }
}
控制器:
public class DropDownController : Controller
{
//
// GET: /DropDown/
public ActionResult Index()
{
var mainItemViewmodel = new MainItemViewModel();
mainItemViewmodel.MainItemId = 2;
mainItemViewmodel.ItemViewModel = new ItemViewModel();
mainItemViewmodel.ItemViewModel.ItemId = 2;
mainItemViewmodel.ItemViewModel.Text = "bla5";
List<SelectListItem> someItems = new List<SelectListItem>(){new SelectListItem(){Value = "1",Text = "Test1"},new SelectListItem(){Value = "2",Text = "Test2"}};
mainItemViewmodel.ItemViewModel.ItemSelectList = someItems;
return View(mainItemViewmodel);
}
[HttpPost]
public ActionResult Index(MainItemViewModel mainItemViewModel)
{
return RedirectToAction("Index");
}
}
下拉\ Index.chtml
@model MainItemViewModel
@using (Html.BeginForm())
{
<br/>
@Html.TextBoxFor(model => model.MainItemId)
<br/>
@Html.EditorFor(model => model.ItemViewModel)
<input name="submit" type="submit" value="submit"/>
}
下拉\ EditorTemplates \ ItemV iewModel.chtml
@model ItemViewModel
@{
@Html.DropDownListFor(model => model.ItemId, Model.ItemSelectList, "Select Item");
<br/>
@Html.TextBoxFor(model => model.Text);
}
的DropDownListFor(型號=> model.ItemId,Model.ItemSelectList, 「選擇項」);不選擇2.我認爲它實際上應該自動選擇你
我一直在做同樣的事情除了具有其他視圖模型中的另一個我所有的下拉列表,它一直很好。
是否與編輯模板和下拉列表的問題,我已看過大多數回答這個問題,我沒有看到,工作 我已經看過這些解決方案的任何一個定論
Problem binding selected value to DropDownListFor inside Editor Template
DropDownListFor - does not select 「Selected」 value
我做的正是通過發送之前設置項目Id ViewModel.If我使用完全相同的模型部分視圖它的作品。我的問題將是爲什麼它與部分視圖(相同的模型),而不是使用editorFor.Right現在我使用部分視圖 – kwiri
是的,我感謝,但這不是我真正想要的。我已經對實際的MVC源代碼(RTM3)進行了一些調試,並且我看到了它們可能是不正確的。它會因爲屬性名稱用於獲取默認選定值的方式而中斷。這就是爲什麼我在編輯器模板中的dropdownlistFor未在部分視圖中選擇正確的值的原因。使用mvc源代碼製作了一個簡單的測試應用程序,並且已經證明了這個下拉式breaks.Strange我注意到,對於文本框,使用了獲取屬性值的不同方法。 – kwiri
這個想法是我想使用dropdownlist的正常方式,而不必添加額外的代碼來做出選擇。我一直在使用像這樣的下拉列表,它工作得很好,它只是這個特定的視圖,我需要在編輯器模板(與下拉列表中)在像我上面描述的視圖 – kwiri