【发布时间】:2015-11-04 13:46:23
【问题描述】:
我是 MVC 和 JQuery 概念的新手,我被困在这里,请帮助
我正在尝试为我的项目实现级联 DropDownList,并且我已经实现了使用 Jquery 函数实现级联 DropDownList
我的问题是,对于我的项目,我需要增加 DropDownList 的数量,因为我创建了一个按钮来增加 DropDownList 的行,但级联 DropDownList 仅适用于第一行,不适用于其他任何其他行下拉列表。
第一行调用JQuery函数实现级联函数,但从第二行开始调用JQuery函数
所以每次选择 DropDownList 中的值时我都需要帮助调用 Jquery 函数
我的代码如下
部分查看代码
@using (Ajax.BeginForm("Index", options))
{
<div class="panel panel-info">
<div class="panel-heading"> </div>
<div class="panel-body">
<div class="form-group col-md-offset-4 ">
@Html.Label("Enter TimeSheet Date:")
@Html.Editor("Date", new { htmlAttributes = new { @class = "form-control datepicker" } })
</div>
<table class="table">
<tr>
<th> </th>
<th> Project </th>
<th> Modules </th>
<th> Task </th>
<th> No of Hours</th>
<th> Note </th>
</tr>
@for(int i=0;i< Model.CountForTimesheetForm; i++)
{
<tr>
<td></td>
<td>@Html.DropDownList("ProjectName", new SelectList(Model.projectList, "Value", "Text")
, "Please Select a Project", new { @class = "form-control" })</td>
<td>
<select id="module" name="module" style="width:200px"></select></td>
<td>@Html.Editor("TaskName", new { htmlAttributes = new { @class = "form-control" } })</td>
<td>@Html.Editor("NoOfHour", new { htmlAttributes = new { @class = "form-control" } })</td>
<td>@Html.Editor("Note", new { htmlAttributes = new { @class = "form-control" } })</td>
</tr>
}
<tr>
<td> <button type="submit" class="btn btn-default">Add Row</button></td>
</tr>
</table>
</div>
</div>
}
Jquery 级联代码
<script language="javascript" type="text/javascript">
$(function () {
$('#ProjectName').change(function () {
$.getJSON('/TimeTracker/GetModules/' + $('#ProjectName').val(), function (data) {
var items = '<option>Select a Modules</option>';
$.each(data, function (i, module) {
items += "<option value='" + module.Value + "'>" + module.Text + "</option>";
});
$('#module').html(items);
});
});
});
【问题讨论】:
-
这段代码有多个问题。您生成的重复
id属性是无效的 html 和$('#ProjectName')只会获得第一个带有id="ProjectName"的元素您还会生成重复的name属性,因此您在回发时无法绑定到您的模型。您需要使用@Html.DropDownListFor(m => m[i].ProjectName, new SelectList(...在for循环中生成控件,并为您的下拉列表类名称提供可用于jQuery 选择器的类名
标签: javascript c# jquery asp.net asp.net-mvc