【问题标题】:Return to the modal in case of error出错时返回模态
【发布时间】:2014-06-30 06:38:01
【问题描述】:

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

[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 jquery asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    你必须做一些javascript。

    1/ 从你的控制器返回 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 form plugin

    $("#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(", "));
            }
        }
    });
    

    【讨论】:

    • 谢谢,但是调用我的模态的地方在哪里,在模态中我有错误,因为我添加了验证
    • @HolgerTans 对不起,我不明白你的评论。
    • 目前我有一个模态弹出窗口,我在控制器中进行了一些验证,如果模态正常,我将数据返回到索引页面,如果不是我希望模态不会关闭并显示错误,我该怎么做?
    • @HolgerTans 我在动作中添加了一行来自动从 ModelState 检索错误
    • 我应该如何调用模态?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2023-03-25
    • 2011-02-17
    • 1970-01-01
    • 2010-12-06
    相关资源
    最近更新 更多