将自定义文本添加到MVC 5的下拉列表中 [英] Add custom text to Dropdown list for MVC 5

查看:37
本文介绍了将自定义文本添加到MVC 5的下拉列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉菜单要添加到MVC 5的_Layout.cshtml页面中.这是从数据库中的参考数据返回的-用于CarTypes.可以选择4种不同类型的汽车模型-轿车,4X4,Estate和掀背车.

I have a dropdown I want to add to my _Layout.cshtml page in MVC 5. This is returned from Reference data in my Database - it is for CarTypes. There are 4 different types of car model that can be selected - Saloon, 4X4, Estate and Hatchback.

我创建了一个CarTypesViewModel,如下所示:

I created a CarTypesViewModel as below:

 public IEnumerable<SelectListItem> CarTypesList { get; set; }

 public string SelectedCarType { get; set; }

然后我有一个观点:

@using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Get))
{
    //Just a html div here perhaps?
    @Html.DropDownListFor(model => model.SelectedCarType, Model.CarTypesList)
}

在布局中,我有以下内容:

Within the layout i have the following:

<li id="selectedcar">@Html.Action("Index", "CarTypes")</li>

然后在我的CarTypes控制器中执行以下操作:

This then goes to this action in my CarTypes controller:

  var model = new CarTypesViewModel 
        {
            CarTypesList= products.Select(p => new SelectListItem
            {
                Value = p.Id.ToString(CultureInfo.InvariantCulture),
                Text = p.Name
            })
        };

        return View(model);

这会将数据返回到下拉列表.但是,我真正想要的是将值显示为请选择您的汽车类型"作为列表中的第一项-实现此目标的最佳方法是什么,因为我不想将其作为值存储在数据库中?

This is returning the data to the Dropdown list. However what I really want is for a Value to appear like Please Select Your Car Type as the first item in the list - what is the best way to achieve that as I dont want to store that as a value in my database?

推荐答案

@Html.DropDownListFor(model => model.SelectedCarType, 
    new SelectList(Model.CarTypesList, "Value", "Text"), 
    "--- Please Select Your Car Type ---", 
    new { @class = "form-control" }
)

这篇关于将自定义文本添加到MVC 5的下拉列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆