简体   繁体   English

在Tag helper .net core中设置默认值

[英]Set default value in Tag helper .net core

I have dropdown list in my page , which uses an enum list to bind. 我的页面中有dropdown列表,它使用enum列表进行绑定。

My enum looks like 我的enum看起来像

  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 . 问题就像PurchaseOrder.PaymentType是一个整数字段,所以这里默认值为0 ,这使我的dropdown始终选择为Cash I know making PurchaseOrder.PaymentType nullable is an option but I want the filed as non nullable. 我知道使PurchaseOrder.PaymentType可以作为一个选项,但我希望该文件不可为空。

I have tired to add value="" in the select also tried selected="selected" in the default option , but nothing is working. 我已经厌倦了在默认选项中的select还试过selected="selected"中添加value="" ,但没有任何工作。

Can someone help me to solve this issue with tag helper syntax? 有人可以帮助我用标记助手语法解决这个问题吗?

Since you have a "blank" option, then your purchase order's PaymentType property should be nullable. 由于您有“空白”选项,因此您的采购订单的PaymentType属性应该可以为空。 You can use the [Required] attribute on it to enforce that the user must actually submit a value. 您可以使用其上的[Required]属性来强制用户必须实际提交值。

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. 始终始终使用视图模型。

You need the SelectList(IEnumerable, String, String, Object, String) overload. 您需要SelectList(IEnumerable,String,String,Object,String)重载。

Initializes a new instance of the SelectList class by using the specified items for the list, the data value field, the data text field, a selected value, and the data group field. 通过使用列表,数据值字段,数据文本字段,选定值和数据组字段的指定项来初始化SelectList类的新实例。

eg in your code: 例如在你的代码中:

SelectList(Model.PaymentTypes, "Id", "Name", 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM