asp.net-mvc Ajax.BeginForm 和验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16635460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ajax.BeginForm and validation
提问by ron
Client side validation is not working for me in Ajax.BeginForm
客户端验证在 Ajax.BeginForm 中对我不起作用
This is my code:
这是我的代码:
<div id="report">
<div id="projectReport">
<div >
@{
Html.EnableClientValidation();
}
@using (Ajax.BeginForm("AnalyticsDates", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "reportContent"
}))
{
@Html.LabelFor(m => m.StartDate)
@Html.TextBoxFor(m => m.StartDate, new { id = "start" })
@Html.ValidationMessageFor(model => model.StartDate)
@Html.LabelFor(m => m.EndDate)
@Html.TextBoxFor(m => m.EndDate, new { id = "end" })
@Html.ValidationMessageFor(model => model.EndDate)
<input id="btnsearch" type="submit" [email protected] class="iconHeader"/>
}
</div>
</div>
<div id="reportContent">
</div>
</div>
And I enabled validation in the web.config page:
我在 web.config 页面中启用了验证:
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
and added js files as well
并添加了js文件
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
second issue related to the first one, my action is
第二个问题与第一个问题有关,我的行动是
[HttpPost]
[Authorize(Roles = "XXXReport")]
public async Task<ActionResult> AnalyticsDates(ReportRequestVM reportRequestVM)
{
if (!ModelState.IsValid)
{
return View("**MainReports**", reportRequestVM);
}
// fill reportRequestVM with data
return View("**PartialReport**", reportRequestVM);
}
If the model is valid I return a partial view and the page looks fine , otherwise I return the main view , with the form , but in this the page renders it self twice. the question is, in case the client validation fails,how to return the main form with the validation errors ?
如果模型有效,我返回一个局部视图并且页面看起来很好,否则我返回主视图和表单,但在这个页面中它自我呈现两次。问题是,如果客户端验证失败,如何返回带有验证错误的主表单?
Any help would be appreciated, 10x Rony
任何帮助将不胜感激,10x Rony
采纳答案by ron
I figured it out... you should have partial view on the result and on the query.
我想通了......你应该对结果和查询有部分看法。
and on failure you should return "http bad request" and use the following to set the validation on the search partial view.
如果失败,您应该返回“http 错误请求”并使用以下内容在搜索部分视图上设置验证。
this is how it should look:
它应该是这样的:
@using (Ajax.BeginForm("CloudAnalyticsDates", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "reportContent",
OnFailure = "OnCloudAnalyticsFailure",
OnBegin = "ValidateForm",
}))
{
@Html.LabelFor(m => m.StartDate)
@Html.TextBoxFor(m => m.StartDate, new { id = "start" })
@Html.ValidationMessageFor(model => model.StartDate)
@Html.LabelFor(m => m.EndDate)
@Html.TextBoxFor(m => m.EndDate, new { id = "end" })
@Html.ValidationMessageFor(model => model.EndDate)
<input id="btnsearch" type="submit" [email protected] class="iconHeader"/>
}
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#datePicker").kendoDatePicker();
$("#start").kendoDatePicker().data("kendoDatePicker");
$("#end").kendoDatePicker().data("kendoDatePicker");
});
function OnCloudAnalyticsFailure(parameters) {
$('#projectReport').html(parameters.responseText);
$('#reportContent').empty();
CleanValidationError('form');
}
</script>
and on the server it should look like:
在服务器上它应该是这样的:
[HttpPost]
public async Task<ActionResult> CloudAnalyticsDates(ReportRequestVM reportRequestVM)
{
if (!ModelState.IsValid)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return PartialView("_ReportQuery", reportRequestVM);
}
reportRequestVM.BomTotals = await CommonRequestsHelper.GetBomTotalAnalytics(bomTotalRequest);
return PartialView("_ProjectReport", reportRequestVM);
}
回答by JTMon
When your modelstate is invalid and you return the view with the model containing the errors, the response sent by the server has an http status of 200 indicating that the request succeeded. In this case, the ajax form does what you instructed it to do which is to insert the returned response into division repostContent (you can verify that by checking that the second rendering of the page is done inside that div). As to how to get an ajax submit form to act the same as normal form submission as far as displaying validation messages, I have not found a simple straight forward method (maybe someone can point one out here :) for us). I solved this by:
当您的模型状态无效并且您返回带有包含错误的模型的视图时,服务器发送的响应的 http 状态为 200,表明请求成功。在这种情况下,ajax 表单执行您指示它执行的操作,即将返回的响应插入分区 repostContent(您可以通过检查页面的第二次渲染是否在该 div 内完成来验证这一点)。至于如何让 ajax 提交表单在显示验证消息方面与普通表单提交相同,我还没有找到一种简单直接的方法(也许有人可以在这里指出一个 :) 给我们)。我通过以下方式解决了这个问题:
- Having the form in a partial view rendered into a div (formDiv) of the main view.
- Having a "OnFailure" specified on the ajax form that inserts the response text into the div that contained the original form (formDiv)
- Override OnActionExecuted (since I have a main controller that all my other ones inherit from this is done in only one place) to check if a request IsAjax and ModelState is invalid, I change the response status to 4xx. This causes the "OnFailure" to get fired replacing the original form with the one returned inside the If(!ModelState.Isvalid) branch.
- 将局部视图中的表单渲染到主视图的 div (formDiv) 中。
- 在 ajax 表单上指定“OnFailure”,将响应文本插入到包含原始表单 (formDiv) 的 div 中
- 覆盖 OnActionExecuted(因为我有一个主控制器,我的所有其他控制器仅在一个地方完成)以检查请求 IsAjax 和 ModelState 是否无效,我将响应状态更改为 4xx。这会导致“OnFailure”被触发,用 If(!ModelState.Isvalid) 分支内返回的表单替换原始表单。

