我创建了一个包含下拉列表的编辑器模板,在发布包装局部视图的表单时,我无法获得所选的值。
@model DDTestViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.DDTestViewModelChild)
<button type="submit" >Submit</button>
}
编辑模板:
@model DDTestViewModelChild
@Html.DropDownListFor(x => x.Items, new SelectList(Model.Items, "ID", "Name", Model.SelectedItemID))
@Html.EditorFor(x => x.SomeOtherValue)
的ViewModels:
public class DDTestViewModel : ViewModelBase
{
public DDTestViewModelChild DDTestViewModelChild { get; set; }
}
public class DDTestViewModelChild
{
public int SelectedItemID { get; set; }
public List<Item> Items { get; set; }
public int SomeOtherValue { get; set; }
}
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
}
控制器:
public virtual ActionResult DDEditorTest()
{
var vm = new DDTestViewModel();
var cvm = new DDTestViewModelChild();
var items = new List<Item>();
items.Add(new Item { ID = 1, Name = "Item 1" });
items.Add(new Item { ID = 2, Name = "Item 2" });
items.Add(new Item { ID = 3, Name = "Item 3" });
items.Add(new Item { ID = 4, Name = "Item 4" });
cvm.Items = items;
vm.DDTestViewModelChild = cvm;
return View(vm);
}
[HttpPost]
public virtual ActionResult DDEditorTest(DDTestViewModel vm)
{
var selectedID = vm.DDTestViewModelChild.SelectedItemID; //selectedID is 0 always
var someOtherValue = vm.DDTestViewModelChild.SomeOtherValue; //this value comes through
return RedirectToAction("DDEditorTest");
}
当我回发到DDEditorTest
时,无论我选择什么,子视图模型的SelectedItemID
都为0,但“SomeOtherValue”来自表单。
我在这里做错了什么?
答案 0 :(得分:1)
您已将其绑定到错误的属性,您必须将其绑定到SelectedItem
,因为下拉列表会发布选项的选定值。
例如:
<select id="SelectedItemID" name="SelectedItemID">
<option value="1">Some Option</option>
</select>
如果在下拉列表中选择了上述选项,则其值属性值将以表单形式发布到操作中。
@Html.DropDownListFor(x => x.SelectedItemID,
new SelectList(Model.Items,
"ID",
"Name",
Model.SelectedItemID))
请参阅Html.DropDownListFor() helper overload documentation和here所有可用的overloads
列表