如何有ajax模式上的错误信息,而不是关闭和打开在整个视图



我有一个Ajax弹出打开一个页面,当一个链接被选中像这样。@Ajax.ModalDialogActionLink("Change your password", "ChangePassword", null, "btn btn-info btn-sm")

当我从表单不正确得到错误时,它关闭模态并带我到错误的整个页面。我的问题是,我如何保持它从关闭和进入整个页面,并有错误显示在模态形式?

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
return RedirectToAction("Index", "Profile", new { tabName = "settings", Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrors(result);
return View(model);
}

我需要它"return"在弹出窗口中显示错误,而不是关闭并重新打开整个页面。顺便说一下,该页面可以以完整或弹出的方式查看。通过页面上的代码

@{
ViewBag.Title = "Change Password";
if (Ajax.IsThisAjaxRequest())
{
Layout = null;
}
else
{
Layout = "~/Views/Shared/_DashboardLayout.cshtml";
}

}

任何帮助将不胜感激,如果你需要看到我的模态对话框扩展只是问..

谢谢你的帮助!

下面的代码在我的项目中被广泛使用。我早些时候尝试过使用它,但没有太大的成功,只有一个"成功"。回报。因为它不具备获取记录Id的能力,因为它使用IdentyModel,而且很多代码实际上是在元数据中。然而,返回一个假,它工作得很好。所以我不得不重新配置代码,这样我才能让它正常工作。由于这种工作方式的很大一部分是在类中编写的,因此该方法对某些人来说没有意义。但是如果你是一个已经编码了一段时间的人,你应该没有问题把它拼凑在一起。我将尽量用最简单的话来解释。

我有一个叫做modaldialogextensions的类。在这堂课上,我有几种不同的用法。用于只是一个链接,链接与css,链接与对象id = @model.Id。这用于打开没有布局的页面的对话框窗口。下面是一个例子。这是打开页面的链接:@Ajax.ModalDialogActionLink("Change your password", "ChangePassword", null, "btn btn-info btn-sm")

sealed class DialogActionResult : ActionResult
{
public DialogActionResult(string message)
{
Message = message ?? string.Empty;
}
string Message { get; set; }
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.Write("<script>   window.location.assign('" + Message + "')   </script>");
}
}
public static MvcHtmlString ModalDialogActionLink(this AjaxHelper ajaxHelper, string linkText, string actionName, string ControllerName, string dialogTitle, string CssClass, object routeValues)
{
var dialogDivId = Guid.NewGuid().ToString();
return ajaxHelper.ActionLink(linkText, actionName, ControllerName, routeValues,
ajaxOptions: new AjaxOptions
{
UpdateTargetId = dialogDivId,
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET",
OnBegin = string.Format(CultureInfo.InvariantCulture, "prepareModalDialog('{0}')", dialogDivId),
OnFailure = string.Format(CultureInfo.InvariantCulture, "clearModalDialog('{0}');alert('You are not authorized to access this area!')", dialogDivId),
OnSuccess = string.Format(CultureInfo.InvariantCulture, "openModalDialog('{0}', '{1}')", dialogDivId, dialogTitle)
}, htmlAttributes: new { @class = CssClass });
}
public static bool IsThisAjaxRequest(this AjaxHelper ajaxHelper)
{
bool result = false;
var currentContext = new HttpContextWrapper(HttpContext.Current);
if (currentContext.Request.Headers["X-Requested-With"] != null
&& currentContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
result = true;
}
return result;
}

public static ActionResult DialogResult(this Controller controller)
{
return DialogResult(controller, string.Empty);
}
public static ActionResult DialogResult(this Controller controller, string message)
{
return new DialogActionResult(message);
}

我只添加了一个MvcHtmlString在这里,为了不张贴整个类。但你也可以添加其他没有全部价值的东西。因为如果一个链接没有对象它将无法工作除非你添加另一个没有对象的链接。当你试图把链接在它将下划线弯弯曲曲的红线,因为你没有一个对象,是必需的。只需复制/粘贴在它下面的类中,并删除routeValues的对象和它的任何实例。

页面也需要一些代码:@Html.StarkAjaxFormSubmiter("frmChangePassword", "tbAspNetUsers", true, "Action Successfully Executed")

的形式是这样的:@using (Html.BeginForm("ChangePassword", "Manage", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmChangePassword" }))

id用于返回成功或错误。在这种特殊情况下,我们将只返回错误。成功将通过一个返回到索引的消息来处理。在这个页面上,我有一个选项卡布局,所以我返回,如果成功,我在页面和选项卡。

这里是控制器代码,我需要帮助的问题。在其他实例中,我通常在尝试后检查模型状态,但这里我已经有一个if(result.Succeeded) so I just used that instead and if it doesn't return Succeeded it will go to the else where I grab theaddererrors (result)sosb.Append '可以填充错误。

新代码:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
try
{
var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
if (user != null)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
}
// not need as the sb.string is working correctly! 
//return RedirectToAction("Index", "Profile", new { tabName = "settings", Message = ManageMessageId.ChangePasswordSuccess });
sb.Append("Sumitted");
return Content(sb.ToString());
}
else
{
AddErrors(result);
foreach (var key in this.ViewData.ModelState.Keys)
{
foreach (var err in this.ViewData.ModelState[key].Errors)
{
sb.Append(err.ErrorMessage + "<br/>");
}
}
}
}          
catch (Exception ex)
{
sb.Append("Error :" + ex.Message);
}
return Content(sb.ToString());
}

如果它确实返回"Success"然后在页面上用JavaScript打开右边的标签页。

<script>
$(document).ready(function () {
var tabName = (window.location.href.match(/[?&]tab-name=[^&$]+/i) || '=').split('=')[1];
if (tabName.length)
$('#myTabs .nav-link[href="#' + tabName + '"]').tab('show');
});

最后是ModalDialogExtensions,这里是

的用法希望这不是太长,但我不想张贴只是新的代码,因为我不认为这将是有意义的大多数谁在看它。还有一个。dll文件是为此定制的,我没有写它,但是我把它给我的东西扩展了它的用途。有兴趣读到这篇文章的人请告诉我,我们会想办法给你。dll文件。

更新:我最终得到了成功的工作,因为它应该,所以我删除了重定向到索引与打开正确的标签,因为这工作正常,没有刷新,它停留在正确的标签"成功"

最新更新