我有2下拉, 第一个是静态'displayAnswer',第二个是'correctAnswer' 在这里我选择'displayAnswer'选项2然后我在'correctAnswer'的第二个下拉列表中只获得1和2, 或者我选择3然后我在'correctAnswer'的第二次下拉中仅获得1,2和3, 或者我选择4然后我在'correctAnswer'的第二个下拉列表中得到1,2,3和4。 使用Mvc Razor Plz帮助我。
thnks。
答案 0 :(得分:0)
无论您使用jQuery
,都可以使用ASP.NET MVC
来实现。这是实现您所需要的一种方式,您可以遵循其他解决方案,但这对我有用。
以下是我的代码中的示例,您可以对其进行修改以适应您的方案。在我的示例中,我将在添加新用户时与部门和单位合作。一个部门由不同的单位组成。因此,当从第一个下拉列表中选择一个部门时,所有部门的单位将在第二个下拉列表中显示。
让我先从视图(页面)开始。它接受名为CreateUserViewModel
的视图模型。应始终使用视图模型,而不是通过域模型。
@model MyProject.ViewModels.Users.CreateUserViewModel
表示我的两个下拉列表的HTML标记:
<tr>
<td class="edit-label">Department <span class="required">*</span></td>
<td>
@Html.DropDownListFor(
x => x.DepartmentId,
new SelectList(Model.Departments, "Id", "Name", Model.DepartmentId),
"-- Select --",
new { id = "Departments" }
)
@Html.ValidationMessageFor(x => x.DepartmentId)
</td>
</tr>
<tr>
<td class="edit-label">Unit <span class="required">*</span></td>
<td>
@Html.DropDownListFor(
x => x.UnitId,
new SelectList(Model.Units, "Id", "Name", Model.UnitId),
"-- Select --",
new { id = "Units" }
)
@Html.ValidationMessageFor(x => x.UnitId)
</td>
</tr>
我的CreateUserViewModel
课程(部分):
public class CreateUserViewModel
{
public int DepartmentId { get; set; }
public IEnumerable<Department> Departments { get; set; }
public int UnitId { get; set; }
public IEnumerable<Unit> Units { get; set; }
}
我的Department
课程:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
}
我的Unit
课程:
public class Unit
{
public int Id { get; set; }
public string Name { get; set; }
public int DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
第一次加载视图时,我会填充部门下拉列表,我将单位下拉为空。
public ActionResult Create()
{
CreateUserViewModel viewModel = new CreateUserViewModel
{
Departments = departmentService.GetAll(),
Units = Enumerable.Empty<Unit>()
};
return View(viewModel);
}
返回我的视图(页面)我使用jQuery
填充第二个下拉列表:
<script>
function resetDropDown(targetDropDown) {
var items = '';
items = '<option>-- Select --</option>';
$(targetDropDown).empty();
$(targetDropDown).html(items);
}
$(document).ready(function () {
$("#Departments").change(function () {
var url = '@Url.Action("GetUnitsByDepartmentId", "User")';
var departmentId = $("#Departments").val();
if (departmentId == '') {
resetDropDown($('#Units'));
return;
}
$.getJSON(url, { departmentId: departmentId }, function (data) {
$('#Units').empty();
var items = '<option>-- Select --</option>';
$.each(data, function (i, unit) {
items += "<option value='" + unit.Id + "'>" + unit.Name + "</option>";
});
$('#Units').html(items);
});
});
});
</script>
在我的控制器中有一个动作方法,它将我的单位作为JSON
结果返回:
public ActionResult GetUnitsByDepartmentId(int departmentId)
{
IEnumerable<Unit> units = unitService.GetUnitsByDepartmentId(departmentId);
var displayedUnits = units.Select(x => new
{
Id = x.Id.ToString(),
Name = x.Name
});
return Json(displayedUnits, JsonRequestBehavior.AllowGet);
}
此解决方案可能并不完美,但它会引导您朝着正确的方向前进。一切顺利。