从jquery脚本调用操作控制器后查看未加载

时间:2015-07-22 10:37:16

标签: jquery asp.net-mvc

我有以下问题: 交换DropDownList的值后,使用脚本调用控制器中的Create操作,模型正确更新,但未在View中显示更改。在View中不显示任何更改,尽管模型已更改,但它仍保持不变。 请告诉我哪里错了。 谢谢。

控制器:

 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) {
        });
    });
});

1 个答案:

答案 0 :(得分:1)

首先,对于从Create()方法返回的视图,您没有做任何事情。你的脚本需要

$("#intructors").change(function () {
  var idselect = $("#intructors").val();
  $.get("/Department/Create", { id: idselect }, function (data) {
    $(someElement).html(data);
  });
});

其中someElement是要插入返回的html的html元素。此外,您的方法需要返回PartialView(model);,而不是View(model);

从评论中,您需要一个额外的方法和部分视图如下

控制器

// 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);
}

Create.cshtml

@model CreateDepartmentViewModel
....
<h3>Instructors</h3>
<div id="Instructors">
  @Html.Partial("_Instructors", Model.Instructors)
</div>
.... // your dropdownlist etc.

_Instructors.cshtml(局部视图)

@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);
  });
});