【问题标题】:how to show data from table in drop down list using MVC3?如何使用 MVC3 在下拉列表中显示表中的数据?
【发布时间】:2012-03-06 07:13:09
【问题描述】:

我正在 mvc3 中创建一个搜索应用程序,其中有 2 个表: 1.State :Id(pk) 和 state_name 2.District:Id(pk),s_id(f.k.), District_name

我首先使用代码和 EF,并为其创建了名为 Search 的数据库

我希望我的索引在下拉列表中显示所有状态

以下是我的 State.cs 代码

public partial class State
{
    public State()
    {
        this.Districts = new HashSet<District>();
        this.Search_master = new HashSet<Search_master>();
    }

    public int Id { get; set; }
    public string State_name { get; set; }

    public virtual ICollection<District> Districts { get; set; }}

这是我的区课:

 public partial class District
{
    public District()
    {
        this.Search_master = new HashSet<Search_master>();
    }

    public int Id { get; set; }
    public string District_name { get; set; }
    public int StateId { get; set; }

    public virtual State State { get; set; } }

我还为州和地区创建了一个视图模型......

  public class State_district
{
    public string selectedstate { get; set; }
    public IEnumerable<State> states { get; set; }
    public string selecteddistrict { get; set; }
    public IEnumerable<District> districts { get; set; }
}

我写的控制器内部:

 public ActionResult Index()
    {
        var model = new State_district { states = db.States, districts = db.Districts };
        return View(model);}

在视图中:

 <div class="editor-field"  id="districtID">*Select State:-
         @Html.DropDownListFor(x => x.states, new SelectList(Model.states, "Id", "State_Name"))
        </div>

有了这个,我可以看到我的第一个 ddl,但是我怎样才能将它与我的第二个列表绑定.....

我需要代码来帮助我只从选定的州向我展示地区.....任何人都可以帮助我使用 jQuery 代码...

提前谢谢你!!

【问题讨论】:

标签: jquery asp.net-mvc asp.net-mvc-3 drop-down-menu


【解决方案1】:

您正在尝试实现动态/级联下拉菜单,互联网上有很多资源可以帮助您:

一个简单的非 AJAX 实现会像这样工作:

你有你的第一个下拉菜单,正常创建:

@Html.DropDownListFor(x => x.states, new SelectList(Model.states, "Id", "State_Name"), new {id = "states"})

您的第二个下拉菜单或依赖下拉菜单将需要存储有关每个项目与哪个父项目相关联的一些信息。例如:

<select name="selecteddistrict" id="districts">
@foreach (var district in Model.districts)
{
    <option value="@district.Id" data-state-id="@district.StateId">@district.District_name</option>
}
</select>

注意下拉列表中的每个条目都有一个附加属性data-state-id。我们需要这些信息才能知道在给定当前活动状态的情况下要显示哪些值。

然后您将添加一个事件处理程序来处理主下拉列表中的更改事件,并相应地更新相关下拉列表:

<script type="text/javascript">

$(function () {
    $("#states").change(onStateChange).change(); // fire for initial setup
});

function onStateChange() {
    var districtDropdown = $('#districts'); 
    districtDropdown.find('option').hide();
    var districtsForState = $(districtDropdown.find('option[data-state-id=' + $(this).val() + ']'));
    districtsForState.show();
    districtDropdown.val(districtsForState.val());
}

</script>

请注意,提供的代码仅用于演示概念。

【讨论】:

  • :非常感谢您...bt data-state-id 无法识别...所以我可以使用 id 代替
  • 您能告诉我如何获取选定的 state-id 并将其传递给 Controller 吗??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 2013-06-16
相关资源
最近更新 更多