skip to Main Content

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" class="form-control js-select">
<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

2

Answers


  1. 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" class="form-control js-select" asp-items="@items"></select>
    
    Login or Signup to reply.
  2. You can use ternary conditional operator in your case:

    @{ string FromAMPM = "AM";  }
    
    <select id="FromAMPM" name="FromAMPM" class="form-control js-select">
      <option value=""></option>
      <option value="AM" @(FromAMPM == "AM" ? "selected='selected'" : "")>AM<</option>
      <option value="PM" @(FromAMPM == "PM" ? "selected='selected'" : "")>PM<</option>
    </select>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search