3 rules
3 rules

Reputation: 1409

Set dropdownlist value selected during Edit in ASP.NET MVC

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.

Upvotes: 0

Views: 5732

Answers (2)

3 rules
3 rules

Reputation: 1409

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/

Upvotes: 0

Saber Fathollahi
Saber Fathollahi

Reputation: 321

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)

Upvotes: 1

Related Questions