如何使DropDownList控件不是必需的

时间:2016-01-19 12:12:30

标签: .net asp.net-mvc razor

在mvc项目中,我有一些可选值,因此需要对应的控制权必须不是强制性的。

属性

[Display(Name = "Transaction type")]
public int TransactionTypeID { get; set; }

用于控制的Razor语法是

<div class="form-group">
@Html.LabelFor(m => m.TransactionType, new { @class = "col-md-3 control-label" })
    <div class="col-md-3">
     @Html.DropDownList("TransactionTypeID", null, "Select tran", new { @placeholder = "Select tran type", @class = "form-control" })
      </div>
    </div>

用于填充控件的控制器语法

private void LoadTransactionTypesInViewData(object selectedValue = null)
{
    var datas = transactionTypeRepository.GetAll().OrderBy(p => p.Name);
    ViewBag.TransactionTypeID = new SelectList(datas, "TransactionTypeID", "Name", selectedValue);
}

为什么我的下拉列表是强制性的,为什么不是可选的。如何使它成为可选项。

1 个答案:

答案 0 :(得分:2)

您需要将属性设为null。你可以通过任何一种方式做到。虽然int?只是Nullable的简写,Nullable本身就是Nullable<Int32>

的简写
[Display(Name = "Transaction type")]
public Nullable<int> TransactionTypeID { get; set; }

[Display(Name = "Transaction type")]
public int? TransactionTypeID { get; set; }
相关问题