【发布时间】:2015-08-14 21:43:08
【问题描述】:
我需要将模型对象传递给控制器,然后从那里调用服务来为局部视图生成数据。我能够将 json 对象传递给主视图,并且能够生成局部视图。但是,在通话后我很难在主视图中呈现部分视图。如果我不将对象传递给控制器,我可以渲染部分视图。
我的主要目标是:传递 json 对象并使用相同的 ajax 调用渲染部分视图。
不胜感激。
对于这里的冗长代码,我深表歉意,但我不确定如何以其他方式做到这一点。
以下代码有效,我不通过 ajax 调用传递 Json 对象,并在控制器中创建部门对象:
主视图代码:
@model PartialViewDemo.Models.School
....
<body>
....
<div>
@Html.Partial("_MyPartialView", Model.Department )
</div>
....
<div id="divTest"></div>
<input type="button" value="Click" id="btnClick"/>
</body>
<script src="~/Content/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function() {
$('#btnClick').click(function(data) {
var dept = {
DepartmentName: "test Dept",
DepartmentRule: "test rule",
Comment:" test comment"
};
$.ajax({
url: '/home/ShowPartailView/',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
});
</script>
控制器代码:
public ActionResult Index()
{
var model = new School();
model.Department = GetDepartmentList(3);
return View(model);
}
public List<Department> GetDepartmentList(int counter)
{
var model = new List<Department>();
for (var i = 1; i <= counter; i++)
{
var data = new Department();
data.DepartmentName = "Dept " + i;
data.DepartmentRule = "Rule " + i;
data.Comment = "Comment " + i;
model.Add(data);
}
return model;
}
public PartialViewResult ShowPartailView()
{
Department dept = new Department()
{
DepartmentName = "test Dept",
DepartmentRule = "test rule",
Comment = "We Rock!"
};
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
部分查看代码:
@model PartialViewDemo.Models.Department
<h2>_MyView from partial view using PartialView</h2>
@if (Model != null)
{
<div>
<table>
<thead>
....
</thead>
<tbody>
<tr>
<td>@Model.DepartmentName</td>
<td>@Model.DepartmentRule</td>
<td>@Model.Comment</td>
</tr>
</tbody>
</table>
</div>
}
型号:
public class Department
{
public string DepartmentName { get; set; }
public string DepartmentRule { get; set; }
public string Comment { get; set; }
}
public class School
{
public List<Department> Department { get; set; }
}
但是,当我将 Json 对象传递给 ajax 调用时,所有其他代码保持不变,除了以下更改外,部分视图不会显示单击事件。
$.ajax({
url: '/home/ShowPartailView/',
data: JSON.stringify(dept),
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
带有控制器代码:
public PartialViewResult ShowPartailView(Department dept)
{
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
【问题讨论】:
-
显示代码!你试过什么?
-
刚刚更新了代码和结果。
-
您可以只使用
data: dept,并删除contentType: ...选项 -
试过了,还是没有雪茄。
标签: ajax json asp.net-mvc