gpt4 book ai didi

jquery - Ajax.BeginForm 添加从 Controller 发送的 ModelSstate 错误?

转载 作者:行者123 更新时间:2023-12-01 04:09:22 24 4
gpt4 key购买 nike

我的 View 中有一个ajax表单

@using (Ajax.BeginForm("AttendeeAvailability", "Response", new AjaxOptions { HttpMethod = "POST", OnSuccess = "done" }))
{
@Html.ValidationSummary(true)
....
//some stuff
....
}
<script type="text/javascript">

function done() {
//do something;
}
</script>

这是 Controller 的post方法

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AttendeeAvailability(AttendeeAvailableDateTime response)
{
....
....
if (somecheck1)
{
ModelState.AddModelError(string.Empty,"Check error1");
return View();
}
if (doesTimeExists2)
{
ModelState.AddModelError(string.Empty,"Check error2");
return View();
}
//do some database actions
return View();
}

目前我没有收到 Controller 中设置的任何 Modelstate 错误消息。

我猜测是因为当 Controller 中的任务成功完成时,它会调用我所看到的done函数。

在这种情况下,如何发送一些错误并将其显示为 Modelstate 错误?

最佳答案

更改表单调用 header (向done函数添加参数):

@using (Ajax.BeginForm("AttendeeAvailability", "Response", 
new AjaxOptions { HttpMethod = "POST", OnSuccess = "done(data)" }))

...和 ​​JavaScript:

<script type="text/javascript">
function done(data) {
//do something with the data
}
</script>

您的数据的外观完全取决于您在操作中如何构造它:

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult AttendeeAvailability(AttendeeAvailableDateTime response)
{
....
....
if (somecheck1)
{
//ModelState.AddModelError(string.Empty,"Check error1");
return Json(new { error = "Check error1" }, JsonRequestBehavior.AllowGet);
}
if (doesTimeExists2)
{
//ModelState.AddModelError(string.Empty,"Check error2");
return Json(new { error = "Check error2" }, JsonRequestBehavior.AllowGet);
}

//do some database actions
return Json(new { success = "Success" }, JsonRequestBehavior.AllowGet);
}

接下来,您可以通过解析来访问数据:

<script type="text/javascript">
function done(data) {
var confirmation = data;
if (confirmation["success"] != undefined) {
alert(confirmation["success"]);
}
else if (confirmation["error"] != undefined) {
alert(confirmation["error"]);
}
}
</script>

关于jquery - Ajax.BeginForm 添加从 Controller 发送的 ModelSstate 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22637736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com