0

I am using Visual Studio 2013 and creating MVC application and I have bind dropdownlist like this:

var list = context.Roles.OrderBy(r => r.Name).ToList()
    .Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name })
    .ToList();  
ViewBag.Roles = list;

and in CSHTML:

@Html.DropDownList("Role", (IEnumerable<SelectListItem>)ViewBag.Roles, "Select ...")

Now I want set selected value in Edit time!

What should I do to select that coming id or name in dropdownlist please help me to do this?

Thanks in advance.

3 rules
  • 1,359
  • 3
  • 26
  • 54
  • You need to set the value of the `Role` property of your model in the GET method before you pass the model to the view (also recommend you use the strongly typed `@Html.DropDownListFor(m => m.Role, ....)` method –  Jun 13 '16 at 07:10
  • @StephenMuecke you mean to say like this @Html.DropDownlistFor(m => m.Role,"Role",(IEnumerable)ViewBag.Roles, "Select ...") right? – 3 rules Jun 13 '16 at 07:11
  • Your binding to a property named `Role`, so you need to set the value of `Role` to match one of the values in your `SelectList` (and you really should be using a view model that contains a property `IEnumerable` in addition to your `string Role` property rather than `ViewBag` –  Jun 13 '16 at 07:14
  • Ok but I am passing the Role with model inside Employee like Role inside the Employee so do I need to create SelectList of Role inside Employee cs file and bind that select list? – 3 rules Jun 13 '16 at 07:17
  • `Employee` is a data model, so no. You should be using a view model that contains the properties your editing plus the property for the `SelectList` - [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Jun 13 '16 at 07:19
  • And its `@Html.DropDownListFor(m => m.Role, (IEnumerable)ViewBag.Roles, "Select ...")` or better (if your using a view model) `@Html.DropDownListFor(m => m.Role, Model.Roles, "Select ...")` –  Jun 13 '16 at 07:21
  • Ohhh ok ok let me try this so I will confirm about it! – 3 rules Jun 13 '16 at 07:22

2 Answers2

1

I am using code like this:

foreach (var c in _countryService.GetAllCountries(true))
   model.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = (c.Id == model.CountryId) });

model.CountryId ====> get edit item id

Working principle this episode:

Selected = (c.Id == model.CountryId)
Saber Fathollahi
  • 311
  • 1
  • 3
  • 10
0

I have done it like this and it's running:

In Back End Code:

var roles = db.RoleTables.ToList();
emp.Role = GetSelectListItems(roles);

private IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<RoleTable> elements)
        {
            foreach (var element in elements)
            {
                selectList.Add(new SelectListItem
                {
                    Value = element.Id,
                    Text = element.Name
                });
            }

            return selectList;
        }

In CSHTML:

@Html.DropDownListFor(model => model.SelectedRole, Model.Role, "Select ...")

Edit time:

var roles = db.RoleTables.ToList();
empreg.Role = GetSelectListItems(roles);
empreg.SelectedRole = db.RoleTable.Where(re => re.Name == employee.Role).Select(r => r.Id).FirstOrDefault();

Thanks to the following post and to those who has responded me: http://nimblegecko.com/using-simple-drop-down-lists-in-ASP-NET-MVC/

3 rules
  • 1,359
  • 3
  • 26
  • 54
  • You `foreach` loop in the `Edit` is pointless and can be removed. Its the value of `SelectedRole` that determines what is selected and the `DropDownListFor()` method builds its own `SelectList` and ignores the `Selected` property of your `SelectListItem`'s –  Jun 13 '16 at 12:13
  • I have to set selected when I am going to edit something that is why I have use that. – 3 rules Jun 13 '16 at 12:37
  • 1
    No you don't. It already selected (internally the `DropDownListFor()` builds a new `SelectList`. Just delete the `foreach` loop and you will still see that its selected :) (the code in your Edit time block is pointless and does nothing. –  Jun 13 '16 at 12:43
  • No dear as per I am testing it is not set I have to do above code for that. – 3 rules Jun 13 '16 at 12:45
  • 1
    Then your doing something else wrong. Your code is utterly pointless! –  Jun 13 '16 at 12:48
  • 1
    And all it needs to be is `emp.Role = roles.Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.Name });` or `emp.Role = new SelectList(roles, "Id", "Name");` –  Jun 13 '16 at 12:53
  • Ohhh awesome I just need to do some practice on better coding thanks for suggest dear sir and yes I know it must select value on SelectedRole but it is not done so where I am going wrong sir! – 3 rules Jun 13 '16 at 13:02
  • 1
    Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/114530/discussion-between-stephen-muecke-and-padhiyar). –  Jun 13 '16 at 13:06