dropdownlist set selected value in MVC3 Razor

283,671

Solution 1

You should use view models and forget about ViewBag Think of it as if it didn't exist. You will see how easier things will become. So define a view model:

public class MyViewModel
{
    public int SelectedCategoryId { get; set; }
    public IEnumerable<SelectListItem> Categories { get; set; } 
}

and then populate this view model from the controller:

public ActionResult NewsEdit(int ID, dms_New dsn)
{
    var 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 model = new MyViewModel
    {
        SelectedCategoryId = dsn.NewsCategoriesID,
        Categories = categories.Select(x => new SelectListItem
        {
            Value = x.NewsCategoriesID.ToString(),
            Text = x.NewsCategoriesName
        })
    };
    return View(model);
}

and finally in your view use the strongly typed DropDownListFor helper:

@model MyViewModel

@Html.DropDownListFor(
    x => x.SelectedCategoryId,
    Model.Categories
)

Solution 2

just in case someone comes with this question, this is how I do it, please forget about the repository object, I'm using the Repository Pattern, you can use your object context to retrieve the entities. And also don't pay attention to my entity names, my entity type Action has nothing to do with an MVC Action.

Controller:

ViewBag.ActionStatusId = new SelectList(repository.GetAll<ActionStatus>(), "ActionStatusId", "Name", myAction.ActionStatusId);

Pay attention that the last variable of the SelectList constructor is the selected value (object selectedValue)

Then this is my view to render it:

<div class="editor-label">
   @Html.LabelFor(model => model.ActionStatusId, "ActionStatus")
</div>
<div class="editor-field">
   @Html.DropDownList("ActionStatusId")
   @Html.ValidationMessageFor(model => model.ActionStatusId)
</div> 

I think it is pretty simple, I hope this helps! :)

Solution 3

I drilled down the formation of the drop down list instead of using @Html.DropDownList(). This is useful if you have to set the value of the dropdown list at runtime in razor instead of controller:

<select id="NewsCategoriesID" name="NewsCategoriesID">
    @foreach (SelectListItem option in ViewBag.NewsCategoriesID)
    {
        <option value="@option.Value" @(option.Value == ViewBag.ValueToSet ? "selected='selected'" : "")>@option.Text</option>

    }
</select>

Solution 4

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" })

Solution 5

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" })
Share:
283,671
Raito Light
Author by

Raito Light

Updated on March 22, 2020

Comments

  • Raito Light
    Raito Light about 4 years

    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.