Specify default value for ASP MVC 3 DropDownListFor

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'

Answers


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()" })

Need Your Help

twitter model associations in rails

ruby-on-rails database-design twitter model

I am trying to build a twitter like data model in rails. This is what I have come up with.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.