Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-tag-helpers

Set default value in Tag helper .net core


I have dropdown list in my page , which uses an enum list to bind.

My enum looks like

  public enum PaymentType
    {
        /// <summary>
        /// The Cash
        /// </summary>
        Cash = 0,

        /// <summary>
        /// The Credit
        /// </summary>
        Credit = 1,

        /// <summary>
        /// The Debit
        /// </summary>
        Debit = 2
    }

And I am binding this enum to the dropdown like below

   <select class="select-text" id="paymentType"  asp-
for="PurchaseOrder.PaymentType" required asp-items="@(new 
SelectList(Model.PaymentTypes, "Id", "Name"))">

<option selected="selected" value ="">--Select payment type--</option>
   </select>

The issue is like PurchaseOrder.PaymentType is an integer filed so here the default value is coming as 0 and this makes my dropdown always selected to Cash. I know making PurchaseOrder.PaymentType nullable is an option but I want the filed as non nullable.

I have tired to add value="" in the select also tried selected="selected" in the default option , but nothing is working.

Can someone help me to solve this issue with tag helper syntax?


Solution

  • Since you have a "blank" option, then your purchase order's PaymentType property should be nullable. You can use the [Required] attribute on it to enforce that the user must actually submit a value.

    If you cannot do that because you're working with your entity class directly, then stop doing that. Always use view models all the time.