Reputation: 10689
I've done this a hundred times but not sure what is going on here. I have a DropDownListFor
that I populate in the controller like so
var mktsegments = from p in db.ChannelMarketSegment
where (p.ChannelCode != "0")
select p;
ViewBag.Pendist = new SelectList(mktsegments, "Pendist", "Pendist");
And in the view, I am attempting to set the default value of this drop down list with the Pendist
value.
EDIT: Pendist is a field that exists in each item pulled into mktsegments
via the Linq
query.
<div class="M-editor-label">
@Html.LabelFor(model => model.Pendist)<span class="req">*</span>
</div>
<div class="M-editor-field">
@Html.DropDownListFor(model => model.Pendist,
(SelectList)ViewBag.Pendist, new { onchange = "ChangeChannel()" })
</div>
However, all this does is set the first value in the list as the default value. If I try to add model => model.Pendist
or Model.Pendist
as the third paramter in the DropDownListFor
like this
@Html.DropDownListFor(model => model.Pendist,
(SelectList)ViewBag.Pendist, model => model.Pendist, new { onchange = "ChangeChannel()" })
I either get the following errors
(for model => model.Pendist
)
Cannot convert lambda expression to type 'string' because it is not a delegate type
(for Model.Pendist
)
'Model' confilcts with the declaration 'System.Web.Mcv.WebViewPage<TModel>.Model'
Upvotes: 1
Views: 2334
Reputation: 93434
You are conflicting with the MVC ModelState. When creating Drow down lists, make sure that your property that holds the selected value is not named the same thing as your list of objects. Also, do not use a lambda for the default value, but rather just use the model item directly.
@Html.DropDownListFor(model => model.Pendist, (SelectList)ViewBag.PendistList,
Model.Pendist, new { onchange = "ChangeChannel()" })
Upvotes: 3