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

时间:2012-08-08 16:29:17

标签: c# asp.net-mvc-2 cascadingdropdown

我正在尝试将一个开发不佳的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的情况下这样做。

1 个答案:

答案 0 :(得分:1)

由于您不能使用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