Populate jquery modal dialog with MVC partial view async, and show in center of screen

我的未来我决定 提交于 2019-12-02 19:28:54

Your code looks fine and it worked when I tested it. Here's my full test case:

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult MyActionOnController()
    {
        // TODO: You could return a PartialView here of course
        return Content("<div>Hello world</div>", "text/html");
    }
}

View (~/Views/Home/Index.cshtml):

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test</title>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" type="text/css" media="all" /> 
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $('#my-dialog').dialog({
                autoOpen: false,
                width: 400,
                resizable: false,
                modal: true
            });

            $('#show-modal').click(function() {
                $('#my-dialog').load("@Url.Action("MyActionOnController")", function() {
                    $(this).dialog('open');
                });
                return false;
            });

        });
    </script>
</head>
<body>
    <div id="my-dialog"></div>
    <a href="#" id="show-modal">Click Me </a>
</body>
</html>

OK, I found the problem:

The partial view I was returning for my modal dialog was created using the MVC scaffolding for an edit view, which by default includes some jQuery scripts which were already included in the layout page, which must have been causing the problem.

All working nicely now!

Possible scope issue?

You're effectively declaring two document.ready functions. Just put all of the code inside:

$(function () {

    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!