c# - Html.DropDownList 默认值 MVC 5

标签 c# asp.net-mvc-5

我只是想向此列表添加默认值(“创建新 field ”),这可能比我做的要容易。我对方法重载感到困惑,特别是因为我使用的重载(由脚手架创建)是 DropDownList(string name, IEnumerable selectList, object htmlAttributes) 并且第二个参数为 null,但它有效。我认为这里有一些惯例在起作用。谁能阐明这一点和/或我如何向此列表添加默认值?

Controller :

ViewBag.VenueId = new SelectList(db.Venues, "Id", "Name", review.VenueId);
        return View(review);
    }   

查看:

<div class="form-group">
        @Html.LabelFor(model => model.VenueId, "VenueId", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("VenueId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.VenueId, "", new { @class = "text-danger" })
            <div>Don't see what you're looking for?  Fear not.  Just type in the name and create your review; we'll fill in the rest!</div>
        </div>
</div>

最佳答案

也许您可以分解您的 SelectList 并向其中插入一个项目?这是一个示例(尚未测试过,所以不能 100% 确定它有效):

Controller

// Create item list from your predefined elements
List<SelectListItem> yourDropDownItems = new SelectList(db.Venues, "Id", "Name", review.VenueId).ToList();

// Create item to add to list
SelectListItem additionalItem = new SelectListItem { Text = "Create new Venue", Value = "0" }; // I'm just making it zero, in case you want to be able to identify it in your post later

// Specify index where you would like to add your item within the list
int ddIndex = yourDropDownItems.Count(); // Could be 0, or place at end of your list?

// Add item at specified location
yourDropDownItems.Insert(ddIndex, additionalItem);

// Send your list to the view
ViewBag.DropDownList = yourDropDownItems;

return View(review);

查看

@Html.LabelFor(model => model.VenueId, new { @class = "form-control" })
    <div>
        @Html.DropDownListFor(model => model.VenueId, ViewBag.DropDownList)
        @Html.ValidationMessageFor(model => model.VenueId)
    </div>
</div>

编辑:

添加默认值的一种方法是在 .DropDownListFor 的最后一个参数中,如下所示:

@Html.DropDownListFor(model => model.VenueId, ViewBag.DropDownList, "Create new Venue")

关于c# - Html.DropDownList 默认值 MVC 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25943189/

相关文章:

c# - 是否有一种方法可以在选择其他语言时获得自定义控件在VS编辑器中显示正确的语言

c# - 检测不活动并取消屏幕保护程序

javascript - 隐藏 'Clear' 按钮,直到单击 'Apply' 按钮

javascript - Google map API 未显示在 MVC5 中

c# - 加载 View 后是否可以在 Controller 中调用操作?

c# - 将颜色定义为静态资源

c# - 在 C# 中使用异步方法进行消息循环

c# - 使用 Linq 获取元组列表

c# - 为什么 Kendo 的 ToDataSourceResult 为一个查询创建两个 ADO.Net 调用

c# - 在 ASP .NET MVC 中更改角色权限