如何在不影响下拉名称的情况下使用 viewbag

how can I use viewbag without affecting the name of dropdown

我想使用 viewbag,但我不想影响下拉列表的名称。我想在下拉列表中使用不同的名称。有没有可能或者有别的解决办法。

我的代码在视图中:

@{
    ViewBag.concurring1 = TempData["pathologistlist"];
 }                            
@Html.DropDownList("concurring", "Select Pathologist")  

还有另一个 overload 的 DropDownList 辅助方法,它允许您生成具有自定义名称和 ID 值的 SELECT 元素

public static MvcHtmlString DropDownList(
    this HtmlHelper htmlHelper,
    string name,
    IEnumerable<SelectListItem> selectList,
    IDictionary<string, object> htmlAttributes
)

因此您的代码将是

@Html.DropDownList("MyCustomName",ViewBag.concurring as List<SelectListItem>,"Select one")  

假设 concurring 存在一个类型为 IEnumerable<SelectListItem>

的 ViewBag 条目
var list= new List<SelectListItem>{
   new SelectListItem { Value="MI", Text="Michigan" },
   new SelectListItem { Value="NY", Text="New York" }
};
ViewBag.concurring = list;

以上代码将生成名称 id 值设置为“MycustomName

的 SELECT 元素