0

I am trying to save values from dropdownlist to the database using MVC 5 + Entity Framework. The values for the dropdownlist are taken from the DB (and displayed), but when I am saving the web entry then the value of the OrderSourceList is null and the OrderSourceId = 0 Model

public class OrderFullModel
{
    [Display(Name = "OrderSource")]
    public IList<SelectListItem> OrderSourceList {get;set;}

    public int OrderSourceId { get; set; }
}

Controller

public ActionResult Create() //this is returning the right dropdownlist
{
    var orderSources = _repository.All<OrderSource>().OrderBy(m => m.NameRu).ToList();
    ViewBag.MyOrderSources = new SelectList(orderSources, "Id", "NameRu", 0);
    return View();
}

View

@Html.LabelFor(m => m.OrderSourceList)
@Html.DropDownListFor(m => m.OrderSourceList, (SelectList)ViewBag.MyOrderSources)    

1 Answer 1

2

The DropDownListFor is a helper that expects an expression for the value in the list you want to display/set, so:

@Html.DropDownListFor(m => m.OrderSourceId, (SelectList)ViewBag.MyOrderSources)  

Currently you're asking for a dropdown to set the value of a list.

From the Docs:

public static MvcHtmlString DropDownListFor(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList)

expression: An expression that identifies the object that contains the properties to display.

selectList: A collection of SelectListItem objects that are used to populate the drop-down list.

Sign up to request clarification or add additional context in comments.

4 Comments

then I am getting Message=The ViewData item that has the key 'OrderSourceId' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.
I would suggest you have a look at this answer for an example of how it all fits together. It seems odd that you have a list of SelectListItems in your model, should that not be a list of OrderSources?
@sidux, You get that error because ViewBag.MyOrderSources is null, most likely because you did not reassign the value in the POST method if you returned the view because ModelState was invalid.
@sidux, But why are you assigning the SelectList to ViewBag? Your model already has a property named OrderSourceList so it should be var model = new OrderFullModel(); model.OrderSourceList = orderSources; return View(model); in the controller and @Html.DropDownListFor(m => m.OrderSourceId, Model.OrderSourceList) in the view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.