Reputation: 24385
I created an editor template that has a dropdown in it, and I can't get the selected value to come through when posting the form that wraps the partial view.
@model DDTestViewModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.DDTestViewModelChild)
<button type="submit" >Submit</button>
}
Editor Template:
@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; }
}
Controller:
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");
}
When I post back to DDEditorTest
the SelectedItemID
of the child view model is 0 no matter what I select, but "SomeOtherValue" comes through from the form.
What am I doing wrong here?
Upvotes: 0
Views: 728
Reputation: 62488
You have binded it to wrong property, you have to bind it to SelectedItem
, as the dropdown will post selected value of the option.
For Example:
<select id="SelectedItemID" name="SelectedItemID">
<option value="1">Some Option</option>
</select>
if the above option is selected in dropdown, its value attribute value will post in the form to action.
@Html.DropDownListFor(x => x.SelectedItemID,
new SelectList(Model.Items,
"ID",
"Name",
Model.SelectedItemID))
See the Html.DropDownListFor() helper overload documentation and here is list of all available overloads
Upvotes: 1