【发布时间】:2015-05-26 02:33:12
【问题描述】:
我想将部分视图返回为 html,以便我可以在 div 中呈现为 html,但它不工作,我无法找到它为什么不工作的问题,这是我的代码。
function getPartial(id) {
$.ajax({
type: "POST",
url: "/Home/GetPartial",
contentType: "application/html",
data: { ID: id },
success: function (response) {
$(".ui-layout-east").html(response);
alert(response);
}
});
}
在我的控制器中,我正在这样做。
[HttpPost]
public ActionResult GetPartial(int ID)
{
var gopal = DataAccess.DataAccess.FillDetailByID(ID);
return PartialView("parent", gopal);
}
但是当我以 json 格式返回时,它可以正常工作,我不明白,请帮我解决这个问题。 以下是我想要返回的部分内容。
@model WebTreeDemo.Models.Employee
<div id="widget">
<div id="x">
@using (Html.BeginForm("Home", "Update", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.EmpCode, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.EmpCode, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.EmpCode, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.JobDesc, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.JobDesc, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.JobDesc, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DateOfJoining, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.DateOfJoining, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.DateOfJoining, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" id="submitButton" value="Save" class="btn btn-default" />
@Html.HiddenFor(x => x.ID)
</div>
</div>
</div>
}
</div> <!-- end of #foo -->
【问题讨论】:
-
内容类型应该是
contentType: "json"(你发送json到控制器)和数据类型应该是dataType: "html"(这是你得到的) -
@Ethan 尝试控制台查看错误。
data: { ID: id }将其更改为data: { 'ID': id }并使用斯蒂芬的评论 -
@StephenMuecke 他没有发送 JSON。在这种情况下,jQuery 会将给定给
data配置的对象转换为查询字符串ID=42(假设id等于42)。要发送 JSON,您必须使用JSON.stringify({ ID: id })对其进行字符串化。事实上,contentType应保持未设置,因此使用默认值application/x-www-form-urlencoded; charset=UTF-8。 -
@TsahiAsher,是的,数据需要被字符串化,或者它可以是
contentType: application/x-www-form-urlencoded。但在任何情况下,它都可以只是$.post('/Home/GetPartial', { ID: id }, function(response) {..- jQuery 会计算出正确的类型。
标签: c# jquery asp.net-mvc