【问题标题】:Getting started, setting up index page开始,设置索引页面
【发布时间】:2016-02-10 23:52:01
【问题描述】:

我刚刚开始使用 MVC,我想在我的索引页面上显示两个 DropDownLists - 索引视图并使用数据库中的唯一状态名称填充第一个下拉列表,并根据第一个下拉列表中的选择填充第二个下拉列表数据来自数据库表中的名称,其中状态等于在第一个下拉列表中选择的状态。

我已经创建了模型类,下面是我的控制器:

public ActionResult Index()
{
    MyRecordContext rc = new MyRecordContext();
    List<MyRecord> rl = rc.MyRecords.ToList();

    return View(rl);
}

在我看来 Index.shtml 我有以下显示第一个下拉列表:

@if (Model != null)
{
    <select id="ddlState">
    @foreach (var item in Model)
    {
        <option>
            @item.State

        </option>

    }
    </select>
}

现在如何确保仅从数据库中选择不同的状态,以及如何根据第一个选择创建和填充第二个下拉列表?有人可以指出我正确的方向吗? 谢谢

更新:

为了在下拉列表中显示不同的状态,我通过以下方式修改了我的控制器:

public ActionResult Index()
{
    MyRecordContext rc = new MyRecordContext();
    List<String> sl = rc.MyRecords.Select(s => s.State).Distinct().ToList();
    return View(sl);
}

【问题讨论】:

标签: asp.net-mvc


【解决方案1】:

在控制器中添加以下行:

ViewBag.ddlState= new SelectList(rl, "valueFieldName", "textFieldName");

在视图中:

@using (Ajax.BeginForm("Index2", new AjaxOptions { UpdateTargetId = "updateTarger" }))
{
    @Html.DropDownList("ddlState", null, String.Empty, new { onchange ="$(this.form).submit()"})
}
<div id="updateTarger"></div>

创建方法:

public ActionResult Index2(string ddlState) // ddlState = value from select, type depends on value
{
    ...
    ViewBag.ddlState2 = new SelectList(rl2, "valueFieldName", "textFieldName");

    return View();
}

和局部视图:

@{
    Layout = null;
}

@Html.DropDownList("ddlState2", null, String.Empty, new { onchange ="$(this.form).submit()"})

你还需要包含"~/Scripts/jquery.unobtrusive-ajax.js"

更改后首先选择它会发送 ajax 请求到 Index2 方法。作为回应,您将获得第二个选择,该选择将放置在 div#updateTarger

【讨论】:

  • 有没有办法在没有 ajax 的情况下做到这一点?
  • 另外我已经有了第一个下拉列表并且它正在被填充,我只需要在第一个下拉列表中进行选择时激活第二个下拉列表
  • 如果第二个下拉列表中的数据取决于第一次选择的选定值,则 ajax 是(在我看来)最简单的方法。您在 javascript 中处理此问题,但随后您将需要从第一个下拉列表中加载所有选项的数据。例如,使用 id 创建 X 隐藏选择取决于第一个下拉值和第一个下拉位置 onchange="$('.secondSelect').hide(); $('#ValueId.secondSelect').show();"
【解决方案2】:

为了在下拉列表中显示不同的状态,我通过以下方式修改了我的控制器:

public ActionResult Index() 
{
    MyRecordContext rc = new MyRecordContext();
    List<String> sl = rc.MyRecords.Select(s => s.State).Distinct().ToList();
    return View(sl);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    相关资源
    最近更新 更多