jupeter
jupeter

Reputation: 746

DropDownList not selected in Edit page

I Created Controller with "MVC 5 Controller with views, using Entity Framework" and modify "DropDownList" code in "Edit" view to

@Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.prdepno, new { @class = "form-control" })

in Controller use ViewBag

personal personal = db.personals.Find(id);

ViewBag.prdepno = new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);

no error ,but dropdownlist not selected

I lookup from Adding a css class to select using @Html.DropDownList() and other question try to do that, but It not work (for me)

I don't know to do (sorry, in my communication.)

Upvotes: 0

Views: 1505

Answers (2)

Mizanur Rahman
Mizanur Rahman

Reputation: 272

Try With this code It's Work properly

Code Generate/ Model

public class CityList
    {
        public string city { get; set; }
    }
public static IEnumerable<SelectListItem> GetCity()
{
    IList<SelectListItem> items = new List<SelectListItem>
    {
        new SelectListItem{Text = "Dhaka", Value = "dhk" },
        new SelectListItem{Text = "Chittagong", Value = "CTG" }
    };
    return items;
}

For Create

ViewBag.city = new SelectList(GetCity(), "Text", "Value");

@Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { @class = "form-control select2", required = "required" })

For edit

ViewBag.city = new SelectList(GetCity(), "Text", "Value",model.city);

@Html.DropDownList("city", null, "--Select city--", htmlAttributes: new { @class = "form-control select2", required = "required" })

You Can Try This it's work fine.

Upvotes: 0

user3966829
user3966829

Reputation:

I think you need to change the name of ViewBag Object

personal personal = db.personals.Find(id);

ViewBag.DwPrdeps= new SelectList(db.prdeps, "prdepno", "prdepdes", emp_map.prdepno);

after that use ViewBag.DwPrdeps in your view

@Html.DropDownListFor(model=>model.prdepno,(SelectList)ViewBag.DwPrdeps, new { @class = "form-control" })

Upvotes: 1

Related Questions