44

OK, I've been Googling for hours and trying everything and can't get anything to work. I am learning MVC using Sharp Architecture and have generated some basic forms for creating Client objects. I want to fill the state drop down list with a list of US states and let the user pick from that list. I am able to populate the list and get the value back (to save the client) but when I go to edit the client, the client's current state is not selected. I have set the selected value in the SelectList:

<li>
    <label for="Client_StateProvince">StateProvince:</label>
    <div>
        <%= Html.DropDownListFor(c=>c.Client.StateProvince, new SelectList(Model.StateProvinces, "id", "Name", Model.Client.StateProvince), "-- Select State --")%>
    </div>
    <%= Html.ValidationMessage("Client.StateProvince")%>
</li>

This does not seem to be good enough. What am I missing?

2
  • Please consider rewriting your question title to be more specific. Commented Aug 19, 2009 at 18:43
  • 1
    What I was needing to do is have an edit page where I edit a (domain object)'s information, in this case a Client object. when I go to edit it, I needed the state part of the form to be a drop down with a list of states (standard stuff), but after it populates it when I am in edit mode, I need it to select the state of the currently editable object. I was populating the drop down, but the current state wasn't selected. once I set the name of the DropDownList (represented by lambda here) to the Id of the state (the value I am using for the value field on the drop down list) I was good to go. Commented Aug 20, 2009 at 0:42

7 Answers 7

78
<%= Html.DropDownListFor(c => c.Client.StateProvince.Id, 
                              new SelectList(Model.StateProvinces, 
                                             "id", 
                                             "Name", 
                                             Model.Client.StateProvince), 
                              "-- Select State --")%>

This does it.

Hope this helps someone else.

~Lee

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

1 Comment

You are right, the first parameter needs to be the same type as the last one. Worked for me too ! Thank you.
7

Worked perfectly for me thanx! I used it to set a parent relation on a subcategory:

<%= Html.DropDownListFor(
 model => model.Category.ParentId,
 new SelectList(Model.Categories,
 "CategoryId",
 "Name",
  Model.Categories.Where(x => x.CategoryId == Model.Category.ParentId).Single()))%>

Jeroen

Comments

4

I did it this way. Works well.

Controller

IFarmModelInterface service2 = new FarmModelRepository();
ViewData["Farms"] = new SelectList(service2.GetFarmNames(), "id", "FarmName", "XenApp");

View

<%: Html.DropDownListFor(m => m.Farm, (ViewData["Farms"] as SelectList)) %>

Comments

3
public ActionResult  AllUsers()
{
    List<Users> users = userRep.GetUsers();
    var listUsers = (from u in users.AsEnumerable()
                     select new SelectListItem
                     {
                        Text = u.UserName,
                        Value = u.UserId.ToString(),
                        Selected = (u.UserId==6)
                     }).AsEnumerable();
    ViewBag.ListItems = listUsers;
    //ViewBag.SelectedItem = 2;
    return View();
}

In AllUsers.cshtml

<p>@Html.DropDownList("ListItems")</p>

Comments

2
<%= Html.DropDownListFor(c => c.Client.StateProvince, new SelectList(Model.StateProvinces, "Id", "Name")) %> 

and override ToString() for StateProvince to return Id, i.e.:

return Id.ToString();

This works but is not a perfect solution...

Dennis

Comments

1

This is View - MVC Controller

@Html.DropDownListFor(m => m.Entity, new ABC.Models.DropDownPopulate().MyMethod, new { @class = "form-control input-inline input-medium" })

MyMethod Get Data List Bind With Dropdown Using SelectListItems

 public List<SelectListItem> MyMethod
        {
            get
            {
                List<SelectListItem> dropdownList = new List<SelectListItem>();
                var items = new DropDown_Bl().GetAll();
                foreach (var item in items)
                {
                    SelectListItem dropdownItem = new SelectListItem();
                    dropdownItem.Value = item.RnID.ToString();
                    dropdownItem.Text = item.Description;
                    dropdownList.Add(dropdownItem);
                }
                dropdownList.Insert(0, new SelectListItem() { Text = "Please Select", Value = "", Selected = true });
                return dropdownList;
            }
        }

GetAll Method In Dropdown_Bl - Used to get data as list from database

  public List<My_Table> GetAll()
        {
            var Items = _Context.MyRepository.GetMany(q => q.Area == "ASD").ToList();
            return Items ;
        }

Comments

0
public ActionResult  AllUsers() {
    List<Users> users = userRep.GetUsers();
    var listUsers = (from u in users.AsEnumerable()
                     select new SelectListItem
                     {
                        Text = u.UserName,
                        Value = u.UserId.ToString(),
                        Selected = (u.UserId==6)
                     }).AsEnumerable();
   // ViewBag.ListItems = listUsers;
   ViewData["tempEmpList"]=listUsers;
    return View(); }

Fill Dropdown

@Html.DropDownList("SelectedEmployee", new SelectList((IEnumerable) ViewData["tempEmpList"], "Id", "Name"))

Comments

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.