简体   繁体   English

在 httppost 后关闭模态窗口

[英]Closing a modal window after httppost

I have a view that displays a list of user roles (eg, administrator, operator, etc) and an "Add" button that pops up a modal window, allowing the user to add a new role.我有一个显示用户角色列表(例如,管理员、操作员等)的视图和一个弹出模式窗口的“添加”按钮,允许用户添加新角色。

In my controller, I have this as my HttpPost method在我的控制器中,我将此作为我的 HttpPost 方法

    [HttpPost]
    public ActionResult Create(RoleModel model)
    {

        if (ModelState.IsValid)
        {
            var role = new RoleDto
                {
                    Name = model.Name,
                    Description = model.Description
                };

            var roleAdded = _rolePermissionsRepository.AddRole(role);
            if (roleAdded != null)
            {
                //CLOSE WINDOW
            }
            else
            {
                //PRINT ERROR MSG TO WINDOW
            }
        }
        return View();
    }

If the add to the DB is successful, I would like to close the modal window, and then refresh the list on my main index page.如果添加到数据库成功,我想关闭模态窗口,然后刷新主索引页面上的列表。

If there's some error while persisting to the DB, the modal window should remain open, and show some error.如果在持久化到数据库时出现一些错误,模态窗口应该保持打开状态,并显示一些错误。

How do I achieve that?我如何做到这一点?

This is what I'm using on my Index page to pop up the window这是我在索引页面上用来弹出窗口的内容

    $("#open").click(function (e) {
        wnd.center();
        wnd.open();
    });

You should return a JsonResult to tell the browser what happened.你应该返回一个 JsonResult 来告诉浏览器发生了什么。

[HttpPost]
public ActionResult Create(RoleModel model)
{

    if (ModelState.IsValid)
    {
        var role = new RoleDto
            {
                Name = model.Name,
                Description = model.Description
            };

        var roleAdded = _rolePermissionsRepository.AddRole(role);
        if (roleAdded != null)
        {
            //CLOSE WINDOW
            return Json(new { success = true });
        }
        else
        {
            return Json(new { error = "Error! Can't Save Data!" });
        }
    }

    return Json(new { error = "Generic Error Message!" });
}

Here is the javascript that should run in your wnd page, you show the error message if there is any, otherwise you close the window.这是应该在您的 wnd 页面中运行的 javascript,如果有错误消息,则显示错误消息,否则关闭窗口。

$('form').submit(function(e) {
    e.preventDefault();
    $.post(this.action, $(this).serialize(), function(response) {
        if(response.error) {
            alert(response.error);
        }
        else {
            wnd.close();
        }
    }, 'json');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM