Home > other >  How to print selected string in select option drop down in csharp cshtml ASP.NET?
How to print selected string in select option drop down in csharp cshtml ASP.NET?

Time:02-23

I new in ASP.NET. I try to print selected string in select option drop down but Compilation error.

Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

Here is my cshtml code.

@{ string FromAMPM = "AM";  }

<select id="FromAMPM" name="FromAMPM" >
<option value=""></option>
<option value="AM" @if (FromAMPM == "AM") { "selected"; } else { ""; }>AM</option>
<option value="PM" @if (FromAMPM == "PM") { "selected"; } else { ""; }>PM</option>
</select>

What wrong? Thanks

CodePudding user response:

You can use ternary conditional operator in your case:

@{ string FromAMPM = "AM";  }

<select id="FromAMPM" name="FromAMPM" >
  <option value=""></option>
  <option value="AM" @(FromAMPM == "AM" ? "selected='selected'" : "")>AM<</option>
  <option value="PM" @(FromAMPM == "PM" ? "selected='selected'" : "")>PM<</option>
</select>

CodePudding user response:

The best way would be separate logic and html

 @{
    var FromAMPM = "PM";
    
    var items = new List<SelectListItem>
    {  
        new SelectListItem { Value= "",   Text="Select" },
        new SelectListItem { Value= "AM",  Text="AM" },
        new SelectListItem { Value="PM",   Text="PM"}
    };
}

you don't neeed selected code, it will automatically select asp-for value

<select id="fromAMPM" asp-for="@FromAMPM"  asp-items="@items"></select>
  • Related