dropdownlist set selected value in MVC3 Razor

2019-01-03 13:22发布

Here is my model:

public class NewsCategoriesModel {
    public int NewsCategoriesID { get; set; }        
    public string NewsCategoriesName { get; set; }
}

My controller:

public ActionResult NewsEdit(int ID, dms_New dsn) {
    dsn = (from a in dc.dms_News where a.NewsID == ID select a).FirstOrDefault();
    var categories = (from b in dc.dms_NewsCategories select b).ToList();
    var selectedValue = dsn.NewsCategoriesID;
    SelectList ListCategories = new SelectList(categories, "NewsCategoriesID", "NewsCategoriesName",selectedValue);

    // ViewBag.NewsCategoriesID = new SelectList(categories as IEnumerable<dms_NewsCategory>, "NewsCategoriesID", "NewsCategoriesName", dsn.NewsCategoriesID);
    ViewBag.NewsCategoriesID = ListCategories;
    return View(dsn);
}

And then my view:

@Html.DropDownList("NewsCategoriesID", (SelectList)ViewBag.NewsCategoriesID)

When i run, the DropDownList does not select the value I set.. It is always selecting the first option.

9条回答
该账号已被封号
2楼-- · 2019-01-03 14:07

Well its very simple in controller you have somthing like this:

-- Controller

ViewBag.Profile_Id = new SelectList(db.Profiles, "Id", "Name", model.Profile_Id);

--View (Option A)

@Html.DropDownList("Profile_Id")

--View (Option B) --> Send a null value to the list

@Html.DropDownList("Profile_Id", null, "-- Choose --", new {  @class = "input-large" })
查看更多
祖国的老花朵
3楼-- · 2019-01-03 14:10

code bellow, get from, goes

Controller:

int DefaultId = 1;
ViewBag.Person = db.XXXX
        .ToList()
        .Select(x => new SelectListItem {
            Value = x.Id.ToString(),
            Text = x.Name,
            Selected = (x.Id == DefaultId)
        });

View:

@Html.DropDownList("Person")

Note: ViewBag.Person and @Html.DropDownList("Person") name should be as in view model

查看更多
贪生不怕死
4楼-- · 2019-01-03 14:13

Replace below line with new updated working code:

@Html.DropDownList("NewsCategoriesID", (SelectList)ViewBag.NewsCategoriesID)

Now Implement new updated working code:

@Html.DropDownListFor(model => model.NewsCategoriesID, ViewBag.NewsCategoriesID as List<SelectListItem>, new {name = "NewsCategoriesID", id = "NewsCategoriesID" })
查看更多
登录 后发表回答