选择要填充html.dropdownlist的值 [英] select the value to populate html.dropdownlist

查看:84
本文介绍了选择要填充html.dropdownlist的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下两节课

public class ODCTE_Major
{
    public int    ODCTE_MajorId { get; set; }
    public string OfficialMajorName      { get; set; }
    public string MajorCode { get; set; }

    ... More unrelated code ....
}

AND

public class CareerMajor
{
    ...lots of unrealted code to this question left out

    public int ODCTE_MajorId { get; set; }
    public virtual ODCTE_Major ODCTE_Major { get; set; }


}

我添加了带有CRUD方法的控制器,并且在create.cshtml中有这行

I added a controller with CRUD methods and in the create.cshtml there is this line

<div class="editor-field">
    @Html.DropDownList("ODCTE_MajorId", String.Empty)
    @Html.ValidationMessageFor(model => model.ODCTE_MajorId)
</div>

选择列表将使用ODCTE_Major中的OfficialMajorName进行填充.我需要选择列表来填充MajorCode或看起来像MajorCode-OfficialMajorName的值.

The select list populates it with the OfficialMajorName from ODCTE_Major. I need the select list to populate with the MajorCode or a value that looks like MajorCode - OfficialMajorName.

请问有人可以提供帮助吗?

Could someone provide assistance for how this is done, please?

谢谢.

推荐答案

将此添加到ODCTE_Major:

Add this to ODCTE_Major:

public string MajorDisplayName
{
    get { return string.Format("{0} - {1}", MajorCode, OfficialMajorName); }
}

这只是一个只读属性,用于创建菜单要使用的格式的显示文本.

This is just a read only property used to create the display text in the format you want the menu to use.

然后在CareerMajor中添加:

Then in CareerMajor, add:

public IEnumerable<ODCTE_Major> Majors{ set; get; } // Thank you Shyju!

这将在视图模型中为您提供一个位置,以将菜单中所需的专业列表传递给视图.

This will give you a place in your view model to pass the list of Majors you want in your menu to the view.

然后在创建要发送到视图的CareerMajor视图模型时,在操作方法中,使用要在菜单中显示的ODCTE_Major实体填充新的IEnumberable.

Then in your action method when you're creating a CareerMajor view model to send to the view, populate the new IEnumberable with the ODCTE_Major entities you'd like displayed in your menu.

在查看页面上:

@Html.DropDownListFor(m => m.ODCTE_MajorId, new SelectList(Model.Majors, "ODCTE_MajorId", "MajorDisplayName", Model.ODCTE_MajorId), "Select One")

这将创建一个SelectList来填充下拉列表.SelectList构造函数表示使用ODCTE_MajorId作为菜单中SelectListItem的值,并使用MajorDisplayName作为实际显示在菜单中的文本.它设置选定的值(如果有),并在菜单顶部添加带有文本选择一个"的空项目.如果您不希望使用null文本,可以随意删除最后一个参数.

This creates a SelectList to populate the drop down with. The SelectList constructor is saying use ODCTE_MajorId as the value for a SelectListItem in the menu, and to use MajorDisplayName as the text to actually display in the menu. It sets the selected value, if there is one, and adds a null item with the text "Select One" to the top of the menu. Feel free to take that final argument out if you don't want the null text.

这篇关于选择要填充html.dropdownlist的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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