Search code examples
c#asp.net-mvcrazor

Showing default selected value in editable dropdown


I've an editable dropdownlist in the cshtml page as follows. I need to show "PT2" as the default selected value in the dropdownlist instead of "Select".

<input id="ProductType" list="ProductTypeList" name="product-type-list" placeholder="Select">
@Html.DropDownListFor(
    model => model.ProductType, new SelectList(model.ProductTypeList,"")  
    )

Model:

public class Product
{

    public string ProductType {get; set;}
    public List<string> ProductTypeList {get; set;}
}
Example values in ProductTypeList : "PT1", "PT2", "PT3"

Wondering if this is possible in the above code? Any thoughts or pointers please??

Thank you.


Solution

  • <input id="ProductType" list="ProductTypeList" name="ProductType" placeholder="@Model.ProductType">
    
    <datalist id="ProductTypeList">
        @foreach (var item in Model.ProductTypeList)
        {
            @if (item == Model.ProductType)
            {
                <option value="@item" selected>@item</option>
               
            }
            else
            {
                <option value="@item" >@item</option>
            }
    
           
        }
    </datalist>