MVC3 Razor和模态弹出窗口

4

我需要一个模态弹出窗口,显示一个表单,并将数据保存回数据库。有没有好的示例?使用Ajax更灵活还是使用jQuery对话框?

3个回答

11

我使用过JQuery UI对话框插件,并使用JQuery通过ajax加载模态对话框,对此非常满意。

为了让您得到有用的东西,我不得不修改我的代码,因此对任何语法错误表示歉意。但是我使用了这个jQuery:

$('#MyAtag').click(function () {
    // Add a container for the modal dialog, or get the existing one
    var dialog = ($('#ModalDialog').length > 0) ? $('#ModalDialog') : $('<div id="ModalDialog" style="display:hidden"></div>').appendTo('body');
    // load the data via ajax
    $.get( 'mycontroller/myaction', {},
        function (responseText, textStatus, XMLHttpRequest) {
            dialog.html(responseText);
            dialog.dialog({
                bgiframe: true,
                modal: true,
                width: 940,
                title: 'My Title'
            }); 
        }
    );
});

这个代码片段绑定了一个Ajax 'get'调用到链接的“click”事件上。该Ajax get请求从我在MVC项目中对应的操作返回一个部分视图,然后在模态对话框中显示。

以下是控制器可能的示例代码。

    public ActionResult MyAction()
    {
        // Do Some stuff
        //...

        // If the request is an ajax one, return the partial view
        if (Request.IsAjaxRequest())
            return PartialView("PartialViewName");

        // Else return the normal view
        return View();
    }

对话框的视图只是一个普通的部分视图。

我使用以下 .css,它会使模态对话框后面的页面变灰。

.ui-widget-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #AAA url(images/ui-bg_flat_0_aaaaaa_40x100.png) 50% 50% repeat-x;
    opacity: .8;
    filter: Alpha(Opacity=30);
}

你可能需要调整#ModalDialog的CSS样式,以使其外观正确。


在视图/控制器中,您不需要做任何与平常不同的事情 - 如果您不想包含_layout.cshtml,则只需返回一个部分视图即可。 - StanK

1

我在我的MVC 3应用程序中使用第一个。虽然不是最好的,但能够运行。 - kheya
你能解释一下你所说的“不是最好的”是什么意思吗?你不喜欢它的哪些方面?我还没有使用过它们,但我很感兴趣。谢谢。 - James Khoury
1
不算最好,我的意思是,如果你遵循第一步,你会知道代码,但它缺乏应用多个主题、特殊效果。但你可以根据需要添加。我喜欢它,因为我不需要那么多的主题样式,我想要更小的脚本大小。希望你也会觉得容易。如果你有问题,请让我知道。 - kheya
如果你遵循第一种方法,应该将CSS放在CSS文件中,将JS代码放在JS文件中,以便更好地重用。 - kheya

1

我们有MVC 3 ASP的示例吗? - Natasha Thapa

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接