Rendering Partial View in code MVC Razor
Asked Answered
C

4

22

I'm using MVC 3 Razor to make a simple CMS for practice purposes, and the idea is that I'm creating a few partial views.

I'm wanting to do a database lookup, and see that 3 partial views need rendering to the page.

How would I do this? In WebForms, you call the LoadControl(ControlURL), but I don't see an equivalent here.

Would it be a client side thing?

Edit - I was more thinking of taking a View name from the model, and then rendering that view rather than knowing the name of the view in advance. So a page might have a view named Foo or a view named Bar. The model, at run time will tell the controller action which view to render.

Cromwell answered 14/10, 2011 at 14:5 Comment(0)
F
54

There are two methods that you can use to render a "control".

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

You can also render other actions.

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

Notice the second of each one is surrounded by @{ } this is because they do not return a string but render directly to the stream.

Forgiving answered 14/10, 2011 at 14:23 Comment(2)
Thanks, with the Html.RenderPartial I'm getting No overload for method 'Write' takes 0 arguments when using it with the @ and {}Cromwell
Sounds like the code generation failed or the call is invalid. Could you paste your call here?Forgiving
J
2

Another way

@RenderPage("~/Views/Shared/LeftMenu.cshtml")
Jobbery answered 6/9, 2018 at 18:3 Comment(0)
M
1

Also, consider @Html.Action() instead of Partial View

Messieurs answered 14/10, 2011 at 14:19 Comment(0)
P
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)
            }
        });
    }
Photothermic answered 3/3, 2016 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.