如果出现错误,返回到模态

Return to the modal in case of error

本文关键字:返回 模态 错误 如果      更新时间:2023-09-26

我在索引页前面有模态窗口,当模型有效时,我重定向到索引视图,但当模型无效时,我希望它留在模态上,我该怎么做?

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(
    [Bind(Include = "Id,name,user,test")] Roles goles)
{
    if (ModelState.IsValid)
    {
        db.GCollection.Add(groupRoles);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    //return View(groupRoles);
    return null;
}

你得写点javascript。

从控制器返回json:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(
    [Bind(Include = "Id,name,user,test")] Roles goles)
{
    if (ModelState.IsValid)
    {
        db.GCollection.Add(groupRoles);
        db.SaveChanges();
        return Json(new {Success=true, Redirect=@Url.Action("Index")});
    }
    var errors = ModelState.Values.SelectMany(v => v.Errors.Select(e => string.IsNullOrEmpty(e.ErrorMessage) ? e.Exception.Message : e.ErrorMessage)).ToArray();
    return Json(new {Success=false, Errors = errors});
}

2/使用ajax提交表单你应该使用jquery表单插件

$("#yourForm").ajaxForm({
    success:function(data){
        if(data.Success===true){
             // in case of success we redirect
             document.location.href= data.Redirect;
        }
        else{
             // Action in case of errors
             alert(data.Errors.join(", "));
        }
    }
});