简体   繁体   English

如何在强类型视图中为下拉列表的可选字符串设置id?

[英]How to set id for optional string for Dropdown in Strongly typed view..?

My Strongly typed view consists of drop-down like below: 我的强类型视图由如下所示的下拉列表组成:

  @Html.DropDownListFor(model => model.Text, ViewBag.Drop as SelectList,"Select a bus");

Above optional string is 'Select a Bus'.But I can't set id property as "0" for this.Remaining id values and text I fetch it from DB.I know I can put even optional string in DB table only.But I don't want like so. 可选字符串上方是“选择总线”。但是我不能为此将id属性设置为“ 0”。剩余的id值和文本是我从DB中获取的。我知道我甚至只能将可选字符串放在DB表中。我不想这样 So if I didn't select anything,and if I submit then 'null' value to Text property of model class in controller method which I don't want.I want's to return only "0" in this case.So My Controller is below. 因此,如果我什么也没选择,并且我向控制器方法中的模型类的Text属性提交了'null'值,那我就不需要。在这种情况下,我只想返回“ 0”。下面。

public ActionResult Dropdown(DropdownCheck drpchk)
    {
        if (ModelState.IsValid)
        {
            return View("some name");
        }

        return View("Dropdown");
    }

So how do I set id value to optional string..? 那么如何将id值设置为可选字符串..?

Add another SelectListItem after retrieving from DB: 从数据库检索后添加另一个SelectListItem

var buses = db.Buses.Select(t => new SelectListItem
{
     Text = t.SomeText,
     Value = t.SomeValue
}).ToList();

buses.Add(new SelectListItem
{
     Text = "--Select a Bus--",
     Value = "0",
     Selected = true
});

ViewBag.Drop = buses;

In your view: 您认为:

 @Html.DropDownListFor(m => m.Text, ViewBag.Drop as IEnumerable<SelectListItem>);

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

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