我有以下问题: 交换 DropDownList 的值后,使用脚本在 Controller 中调用 Create 操作,模型已正确更新,但 View 中未显示更改。 View 中不显示任何变化,尽管模型发生了变化,但它保持不变。 请告诉我哪里错了。 谢谢。
Controller :
public ActionResult Create(int? id)
{
IEnumerable<Instructor> selIns = db.Instructors.Where(x => x.ID == id);
var model = new CreateDepartmentViewModel
{
Department = new Department(),
Instructors = selIns,
};
return View(model);
}
查看:
@if (Model.Instructors != null)
{
<h3>
Instructors
</h3>
<table class="table">
<tr>
<th>Name</th>
<th>Grade</th>
</tr>
@foreach (var item in Model.Instructors)
{
<tr>
<td>
@item.FullName
</td>
<td>
@Html.DisplayFor(modelItem => item.HireDate)
</td>
</tr>
}
</table>
}
….
@Html.DropDownListFor(x => x.Department.InstructorID, Model.InstructorIds, htmlAttributes: new { @id = "intructors", @class = "form-control" })
…..
$(document).ready(function () {
$("#intructors").change(function () {
var idselect = $("#intructors").val();
$.get("/Department/Create", { id: idselect }, function (data) {
});
});
});
最佳答案
首先,您没有对从 Create() 方法返回的 View 执行任何操作。您的脚本需要是
$("#intructors").change(function () {
var idselect = $("#intructors").val();
$.get("/Department/Create", { id: idselect }, function (data) {
$(someElement).html(data);
});
});
其中 someElement
是要在其中插入返回的 html 的 html 元素。此外,您的方法需要返回 PartialView(model);
,而不是 View(model);
。
从评论中,您需要额外的方法和部分 View ,如下所示
Controller
// The main method for additional generating you view
public ActionResult Create(int? id)
{
....
return View(model);
}
// The method that is called by your ajax call
public ActionResult FetchInstructors(int id)
{
// note the following line would fail if parameter id is null so it should be int id, not int? id
IEnumerable<Instructor> model = db.Instructors.Where(x => x.ID == id);
return PartialView("_Instructors", model);
}
创建.cshtml
@model CreateDepartmentViewModel
....
<h3>Instructors</h3>
<div id="Instructors">
@Html.Partial("_Instructors", Model.Instructors)
</div>
.... // your dropdownlist etc.
_Instructors.cshtml(部分 View )
@model IEnumerable<Instructor>
<table>
<thead>
....
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.FullName</td>
<td>@Html.DisplayFor(m => item.HireDate)</td>
</tr>
}
</tbody>
</table>
然后脚本(在Create.cshtml
中)需要是
var placeholder = $('#Instructors'); // cache it
var url = '@Url.Action("FetchInstructors", "Department")'; // don't hard code you url's
$("#intructors").change(function () {
var idselect = $(this).val(); // use $(this) so you don't traverse the DOM again
$.get(url, { id: idselect }, function (data) {
placeholder.html(data);
});
});
关于jquery - 从 jquery 脚本调用操作 Controller 后 View 未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31560705/