Issue
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
Solution
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>
Answered By – Rahul Sharma
Answer Checked By – Candace Johnson (BugsFixing Volunteer)