14

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

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
rusty coder
  • 157
  • 1
  • 1
  • 4

7 Answers7

35

If you have a static list of options, for example, for Marital Status, you can keep it more legible (for some of us) like this:

<select>
  <option value="Single"   @(marStat == "Single"   ? "selected" : "")>Single</option>
  <option value="Married"  @(marStat == "Married"  ? "selected" : "")>Married</option>
  <option value="Divorced" @(marStat == "Divorced" ? "selected" : "")>Divorced</option>
  <option value="Widowed"  @(marStat == "Widowed"  ? "selected" : "")>Widowed</option>
</select>

What this does is that if your razor variable marStat containing the value that you retrieved from the database matches the string in the condition, it renders "selected" into the HTML. It's a bit of "brute" style but I believe it's very readable.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
Amarundo
  • 2,357
  • 15
  • 50
  • 68
  • 8
    I have code very similar to this, but I get `The tag helper 'option' must not have C# in the element's attribute declaration area.` Guessing this is obsolete Razor syntax. – Grant Birchmeier Dec 21 '20 at 19:30
  • 6
    I had the same issue as @GrantBirchmeier so just for completeness sake, I fixed it by using ` where marStat was declared in the select item as value – RDAxRoadkill May 18 '21 at 19:01
  • 3
    If you have "selected" at all in the attributes, it will select it. "selected:", "selected=false" all will set it selected. – Darryn Frost Mar 18 '22 at 22:10
  • @RDAxRoadkill solution works even in Razor components while the main answer did not. Code with highlighting below: https://stackoverflow.com/a/75788203/6761698 – Wouter Vanherck Mar 20 '23 at 08:56
6

In .NET 6:

use asp-for="@selectedValue"

@{
 string selectedValue = "en-us"
}
<select name="culture" asp-for="@selectedValue">
  <option value="pt-br">Português (Brasil)</option>
  <option value="en-us">English (United States)</option>
</select>

At runtime .NET will set the selected attribute tag.

Lucio Pelinson
  • 430
  • 5
  • 7
6

in the layout site:

@{
    if (!IsPost)
    {
        PageData["accountType"] = 0; /* default value */
    }
}
<html>
    <head></head>
    <body>
        <form action="@Href("~/")" method="post">
            <select name="accountType">
                <option value="0"@(PageData["accountType"] == 0 ? " selected" : "")>Standard</option>
                <option value="1"@(PageData["accountType"] == 1 ? " selected" : "")>Golden</option>
                <option value="2"@(PageData["accountType"] == 2 ? " selected" : "")>Ultimate</option>
            </select>
        </form>
    </body>
<html>

and on the other site you can access it with something like

var accountType = Convert.ToInt32(Request["accountType"]);

later set it for your needs with

PageData["accountType"] = (required int value);
bviktor
  • 215
  • 4
  • 2
4

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.

  • I'm not sure if this code will work, since I'm writing it by memory
dtc
  • 10,136
  • 16
  • 78
  • 104
  • 'System.Web.Mvc.HtmlHelper' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax. – Mehman Bashirov Sep 19 '14 at 07:52
0

Felt it good to add this as well - which is how I did it. You can also pass the value to the ViewBag from with the controller and grab it and make the comparison within the view. See below: Here in the view I pass the value to to the ViewBag -

ViewBag.degreeLevel = userInfo.educationlevel; (user info is just my object)

Then, I make the comparisons in the view, like below: enter image description here

0

While @bviktor's answer seems to work for regular Razor pages, it does not work for Razor components as the view inserts @(isSelected ? in the option. So I tried @RDAxRoadkill's solution, which worked in my Razor component. I'd also recommend writing the check on a separate line for readability.

    <select id="yourSelectId" name="yourSelectName">
        @foreach(var obj in objList)
        {
            bool isSelected = obj.Key == expectedKey;
    
            <!-- Works in Razor views -->
            <!option value="obj.Key" @(isSelected ? "selected" : "")>
                @obj.Value
            </!option>
    
            <!-- Works in Razor components -->
            <!option value="obj.Key" selected=@isSelected>
                @obj.Value
            </!option>
        }
    </select>
Wouter Vanherck
  • 2,070
  • 3
  • 27
  • 41
0

This worked for me

<select class="form-control" id="destinationId" name="DestinationId">
                                @foreach (var destination in Model.Destinations)
                                {
                                    if (destination.Id == d.DestinationId)
                                    {
                                        <option value="@destination.Id" selected="selected">@destination.DestinationName</option>
                                    }
                                    else
                                    {
                                        <option value="@destination.Id">@destination.DestinationName</option>
                                    }
                                }
                            </select>
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • There are **six existing answers** to this question, including a top-voted, accepted answer with over **thirty votes**. Are you _certain_ your solution hasn't already been given? If not, why do you believe your approach improves upon the existing proposals, which have been validated by the community? Offering an explanation is _always_ useful on Stack Overflow, but it's _especially_ important where the question has been resolved to the satisfaction of both the OP and the community. Help readers out by explaining what your answer does different and when it might be preferred. – Jeremy Caney Aug 11 '23 at 00:45