Reputation: 779
I have a viewmodel as below :
public class WhItemForm
{
public virtual WhItem WhItem { get; set; }
public virtual WhItemStock WhItemStock { get; set; }
}
And in my controller, i use ViewBag to fill the select list as below :
public ActionResult Create()
{
ViewBag.WhBrandId = new SelectList(db.WhBrand, "Id", "Name");
ViewBag.WhStockCardId = new SelectList(db.WhStockCard, "Id", "Name");
ViewBag.WhLocationId = new SelectList(db.WhLocation, "Id", "Name");
return View();
}
I have BrandID property in my WHITEM model, here is my WHITEM model .
public class WhItem
{
public int Id { get; set; }
public int WhBrandId { get; set; }
public virtual WhBrand WhBrand { get; set; }
}
When i post the data from view, i am not able to set WhBrandID, my view as below :
<div class="form-group">
@Html.LabelFor(model => model.WhItem.WhBrandId, "WhBrandId", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("WhBrandId", String.Empty)
@Html.ValidationMessageFor(model => model.WhItem.WhBrandId)
</div>
</div>
I know, i need to pass this value as WhItem.WhBrandId since i am using viewmodel in my view. I can do this for @html.TextBoxFor but how can i correct my dropdown list to pass its value as WhItem.WhBrandId to the controller.
Regards
Upvotes: 1
Views: 1980
Reputation: 661
First i suggest you edit your controller like this:
public ActionResult Create()
{
ViewBag.SelectList = new List<SelectListItem>
{
new SelectListItem{Text = "Text",Value = "Value"},
new SelectListItem{Text = "Text",Value = "Value"},
new SelectListItem{Text = "Text",Value = "Value"}
};
return View();
}
After that edit your view to this:
@Html.DropDownListFor(x => x.WhItem.WhBrandId, (List<SelectListItem>)ViewBag.SelectList)
Upvotes: 4