我在结果表上方的页面中有一个小的部分创建人员表单。我希望能够将表单发布到服务器,我可以使用 ajax.Beginform 做到这一点。
<% using (Ajax.BeginForm("Create", new AjaxOptions { OnComplete = "ProcessResponse" }))
{%>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%=Html.LabelFor(model => model.FirstName)%>
</div>
<div class="editor-field">
<%=Html.TextBoxFor(model => model.FirstName)%>
<%=Html.ValidationMessageFor(model => model.FirstName)%>
</div>
<div class="editor-label">
<%=Html.LabelFor(model => model.LastName)%>
</div>
<div class="editor-field">
<%=Html.TextBoxFor(model => model.LastName)%>
<%=Html.ValidationMessageFor(model => model.LastName)%>
</div>
<p>
<input type="submit" />
</p>
</fieldset>
<%
}
%>
然后在我的 Controller 中,我希望能够回发一个部分,它只是一个表行 如果创建成功并将其附加到表中,我可以使用 jquery 轻松完成。
$('#personTable tr:last').after(data);
但是,如果服务器验证失败,我想传回包含验证错误的部分创建人员表单,并替换现有的创建人员表单。
我试过返回一个 Json 数组
Controller :
return Json(new
{
Success = true,
Html= this.RenderViewToString("PersonSubform",person)
});
Javascript:
var json_data = response.get_response().get_object();
带有通过/失败标志,部分使用下面的 solition 呈现为字符串,但在表单失败时不呈现 mvc 验证控件。
那么,有什么方法可以让我的 javascript 直接从我的 ajax.form 返回 PartialView("PersonForm") 吗?我可以将一些附加信息作为 Json 数组传递,以便判断它是通过还是失败,并可能添加一条消息吗?
更新
我现在可以将 PartialView 的 HTML 传递给我的 javascript,但我需要传递一些额外的数据对,例如 ServerValidation:true/false 和 ActionMessage:“您刚刚创建了一个个人账单”。理想情况下,我会在我的部分中传递一个 Json 数组而不是隐藏字段。
function ProcessResponse(response) {
var html = response.get_data();
$("#campaignSubform").html(html);
}
提前致谢
请您参考如下方法:
我在这种情况下所做的实际上是呈现出包含所有信息(例如验证信息等)的部分 View ,然后使用 jquery 中的 DOM 函数提取我需要的内容,如果它不仅仅是用于显示的话.以这种方式将所有内容保存为一种格式,我不必担心同时处理 json 和 html。
