[asp.net-mvc-3] dropdownlist set selected value in MVC3 Razor

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.

This question is related to asp.net-mvc-3 drop-down-menu razor selected

The answer is


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

To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.

ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");

I want to put the correct answer in here, just in case others are having this problem like I was. If you hate the ViewBag, fine don't use it, but the real problem with the code in the question is that the same name is being used for both the model property and the selectlist as was pointed out by @RickAndMSFT

Simply changing the name of the DropDownList control should resolve the issue, like so:

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

It doesn't really have anything to do with using the ViewBag or not using the ViewBag as you can have a name collision with the control regardless.


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

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>

I prefer the lambda form of the DropDownList helper - see MVC 3 Layout Page, Razor Template, and DropdownList

If you want to use the SelectList, then I think this bug report might assist - http://aspnet.codeplex.com/workitem/4932


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


For anyone that dont want to or dont make sense to use dropdownlistfor, here is how I did it in jQuery with .NET MVC set up.

  1. Front end Javascript -> getting data from model:
    var settings = @Html.Raw(Json.Encode(Model.GlobalSetting.NotificationFrequencySettings)); 

    SelectNotificationSettings(settings);

    function SelectNotificationSettings(settings) {
                $.each(settings, function (i, value) {
                    $("#" + value.NotificationItemTypeId + " option[value=" + value.NotificationFrequencyTypeId + "]").prop("selected", true);
                });
    }
  1. In razor html, you going to have few dropdownlist
 @Html.DropDownList(NotificationItemTypeEnum.GenerateSubscriptionNotification.ToString,
    notificationFrequencyOptions, optionLabel:=DbRes.T("Default", "CommonLabels"),
    htmlAttributes:=New With {.class = "form-control notification-item-type", .id = Convert.ToInt32(NotificationItemTypeEnum.GenerateSubscriptionNotification)})

And when page load, you js function is going to set the selected option based on value that's stored in @model.

Cheers.


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! :)


Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC

Examples related to selected

UITableViewCell Selected Background Color on Multiple Selection How can I disable selected attribute from select2() dropdown Jquery? How to set a selected option of a dropdown list control using angular JS How to set the 'selected option' of a select dropdown list with jquery html select option SELECTED How to check if "Radiobutton" is checked? Programmatically select a row in JTable dropdownlist set selected value in MVC3 Razor UIButton: set image for selected-highlighted state jQuery remove selected option from this