C# MVC2:如何获取下拉列表的选定值

本文关键字:下拉列表 获取 MVC2 何获取 | 更新日期: 2024-11-06 01:42:45

我正在尝试将开发不佳的 C# Web 应用程序转换为 MVC2,并且在尝试构建级联下拉列表时遇到困难。这是代码:

public IEnumerable<SelectListItem> SchoolList
    {
        get
        {
            DataTable dt = ClassModels.GetSchools();
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(new SelectListItem
                {
                    Text = Convert.ToString(row["School"]),
                    Value = Convert.ToString(row["SID"]),
                });
            }
            return list;
        }
    }
    public IEnumerable<SelectListItem> DepartmentList
    {
        get
        {
            DataTable dt = DomData.GetDepartments(this is where the selected SID goes)
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (DataRow row in dt.Rows)
            {
                list.Add(new SelectListItem
                {
                    Text = Convert.ToString(row["Department"]),
                    Value = Convert.ToString(row["DID"]),
                });
            }
            return list;
        }
    }

这是各部门的模式

public static DataTable GetDepartments(int id)
    {
        string sql = string.Format(@"SELECT d.department, d.did
            FROM dept d
            WHERE d.did IN (SELECT DISTINCT(DID) FROM CDS WHERE SID = '{0}')
            ORDER BY department", id);
        DataTable db_table = new DataTable("departments");
        SqlDataAdapter db_adapter = new SqlDataAdapter(sql, iau_conxn_string);
        db_adapter.Fill(db_table);
        //ddl_dep.DataSource = db_table;
        //ddl_dep.DataValueField = "did";
        //ddl_dep.DataTextField = "department";
        //ddl_dep.DataBind();
        return db_table;
    }

可悲的是,我必须在没有AJAX或jQuery的情况下做到这一点。

C# MVC2:如何获取下拉列表的选定值

由于您不能使用 AJAX,而只能使用纯 javascript,因此您可以订阅第一个下拉列表的 onchange 事件,然后提交表单以填充第二个下拉列表。

但在将其付诸行动之前,让我们先定义一个视图模型。在我的示例中,我显然会删除问题中存在的所有干扰(例如 DataTables 和数据访问特定代码,并简单地对值进行硬编码,以便答案更通用,因此只需将这些硬编码值替换为对数据访问方法的调用):

public class MyViewModel
{
    public MyViewModel()
    {
        Departments = Enumerable.Empty<SelectListItem>();
    }
    public int? SchoolId { get; set; }
    public IEnumerable<SelectListItem> SchoolList
    {
        get
        {
            // TODO: fetch the schools from a DB or something
            return new[]
            {
                new SelectListItem { Value = "1", Text = "school 1" },
                new SelectListItem { Value = "2", Text = "school 2" },
            };
        }
    }
    public int? DepartmentId { get; set; }
    public IEnumerable<SelectListItem> Departments { get; set; }
}

然后是控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }
    [HttpPost]
    public ActionResult Departments(MyViewModel model)
    {
        // TODO: use model.SchoolId to fetch the corresponding departments
        // from your database or something
        model.Departments = new[]
        {
            new SelectListItem { Value = "1", Text = "department 1 for school id " + model.SchoolId },
            new SelectListItem { Value = "2", Text = "department 2 for school id " + model.SchoolId },
            new SelectListItem { Value = "3", Text = "department 3 for school id " + model.SchoolId },
        };
        return View("Index", model);
    }
}

最后是视图:

<%@ Page 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewPage<MyViewModel>" 
%>
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myform", data_departments_url = Url.Action("Departments") })) { %>
    <div>
        <%= Html.LabelFor(x => x.SchoolId) %>
        <%= Html.DropDownListFor(
            x => x.SchoolId, 
            Model.SchoolList, 
            "-- School --",
            new { id = "school" }
        ) %>
    </div>
    <div>
        <%= Html.LabelFor(x => x.DepartmentId) %>
        <%= Html.DropDownListFor(
            x => x.DepartmentId, 
            Model.Departments,
            "-- Department --"
        ) %>
    </div>
<% } %>

最后一点当然是 JavaScript 订阅第一个下拉列表的 onchange 事件并将表单提交到服务器以填充第二个下拉列表:

window.onload = function () {
    document.getElementById('school').onchange = function () {
        if (this.value) {
            var form = document.getElementById('myform');
            form.action = form.getAttribute('data-departments-url');
            form.submit();
        }
    };
};

对于那些没有与您相同的约束并且可以使用 AJAX 和 jQuery 的人,请查看以下答案: https://stackoverflow.com/a/4459084/29407