在MVC Razor中使用代码呈现局部视图

22

我正在使用MVC 3 Razor创建一个简单的CMS项目来进行练习,我的想法是要创建几个局部视图。

我希望通过数据库查找来渲染3个局部视图到页面中。

我该如何实现呢?在WebForms中,您可以调用LoadControl(ControlURL)方法,但我在这里没有找到等价的方法。

这是客户端的事情吗?

编辑 - 我更多地是考虑从模型中获取视图名称,然后渲染该视图,而不是预先知道视图的名称。因此,页面可能具有名为Foo或Bar的视图。在运行时,模型将告诉控制器动作渲染哪个视图。

4个回答

54

你可以使用两种方法来渲染一个"控件(control)"。

@Html.Partial("ViewName")
@{ Html.RenderPartial("ViewName"); }

你也可以渲染其他操作。

@Html.Action("ActionName", "Controller", new { Values = "yourvalues" })
@{ Html.RenderAction("ActionName", "Controller", new { Values = "yourvalues" }); }

注意每个中括号的第二个都被 @{ } 包围,这是因为它们不返回字符串,而是直接渲染到流中。


谢谢,使用Html.RenderPartial时,当与@和{}一起使用时,我得到了“Write”方法没有接受0个参数的重载。 - Paul
听起来代码生成失败了或者调用是无效的。你能把你的调用粘贴在这里吗? - Buildstarted

2

另一种方式

@RenderPage("~/Views/Shared/LeftMenu.cshtml")

1
Html.RenderPartial("partialview name", Model.class, new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "classname" } });

This code can be used to render the partial view in apge.
HTMLfiledprefix is defined to keep the data available in the model

You can use tis code to load a partial view on a button event using ajax
 function partialview() {
        var url = '@Url.Action("action", "controller")';
        var data = $('#frm').serialize();
(to serialize the data in the model before posting to the action)
        var finaldata = data;
        $.ajax({
            type: "post",
            url: url,
            data: finaldata,
            async: false,
            contentType: "application/json; charset=utf-8",
            error: function (xhr) {
                errorRedirecttoErrorController(xhr.error);
            },
            success: function (data) {
                $("#DIVID").html(data);
(div to which the partial view to be loaded)
            }
        });
    }

1

此外,考虑使用@Html.Action()而不是局部视图


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