razorwebmatrix

How to set the value of a select element's selected property


I am using webmatrix, razor syntax and cshtml file.

I have an "edit" page for a database record which contains a select box(id="selStatus"). I am trying to set the "selected" value of the select box dynamically, based on the value of the current record being edited.

I have the current value or its index in local var's but i cant seem to assign this value back to the select.

if (currentStatus=="Completed"){
    selStatus.options[1].selected=true;
}

RES = error: The name 'selStatus' does not exist in the current context.

I am missing something obvious here but can't seem to get it. Any ideas appreciated. Thanks


Solution

  • Besides using Javascript you can set the selected item when you create the dropdown.

    This will work when you have a dynamically generated dropdown. If your dropdown is static then you need to use javascript.

    First create the data that will fill the dropdown:

    var selectQ = "SELECT StatusName, StatusID FROM MyStatusTable";
    List<SelectListItem> statusdropdownlistdata = new List<SelectListItem>();
    bool isSelected = false;
    foreach(var item in db.Query(selectQ)){
        isSelected = false;
        if(item.StatusName == "Completed"){
            isSelected = true;
        }
        statusdropdownlistdata.Add(new SelectList Item
        {
            Text = item.StatusName,
            Value = item.StatusID.ToString(), 
            Selected = isSelected
        });
    }
    

    The above will create the data you want to add to your dropdown and select an item that meets criteria. You'll have to modify to work with your specific criteria and logic.

    Next, add this to the HTML part of your cshtml:

    @Html.DropDownList("StatusTypes", statusdropdownlistdata)
    

    The above will render the dropdown list with an ID="StatusTypes" and your dropdown data with selected item.

    Look up Html.DropdownList and you'll probably be able to find other options and ways to do this.