asp.net-mvcvisual-studioasp.net-corerazorasp.net-core-mvc

How to create select element with selected option in shopping cart view


In ASP.NET Core 5 MVC shopping cart Razor view in used to create cart layout selector.

In ASP.NET MVC 4.7 it works OK but in .NET Core lines which set selected option

<option value="List" @(Model.LocatorViewModel.CartLayout == CartLayout.List ? "selected" : "" )>

show syntax error in razor editor in VS 2019:

enter image description here

Which is property method to create select element selected attribute in Razor? Bootstrap 3 is used.

   <div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne">
     <div class="panel-body">
      <label>
       @await I.I("Display mode")
       <select name="cartlayout" class="form-control" onchange="this.form.submit()">
       <option value="List" @(Model.LocatorViewModel.CartLayout == CartLayout.List ? "selected" : "" )>
       @await I.I("List")
       </option>

     <option value="Thumb" @(Model.LocatorViewModel.CartLayout == CartLayout.Thumb ? "selected" : "" )>
      @await I.I("Thumbnails")
      </option>
    </select>
    </label>
   </div>
 </div>

Solution

  • As error message indicated, the 'OptionTagHelper' can not have C# in the element's attribute declaration area.

    In the code you shared, it seems that the option works as just plain HTML <option> in your scenario. If so, you can try to apply @removeTagHelper to a specific view that would help remove the specified Tag Helper from the view.

    @removeTagHelper Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper, Microsoft.AspNetCore.Mvc.TagHelpers 
    

    Test Result

    enter image description here