Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering Partial View in code MVC Razor

Tags:

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.

like image 967
Paul Avatar asked Oct 14 '11 14:10

Paul


People also ask

How do I render a partial view in Razor?

For this go to Solution Explorer then select Views -> Shared Folder -> Right-click -> Add View. Now for the View -> Home -> Index. cshtml. Here I am rendering a Partial View using 4 types, so the index.

Which is the way to render partial view using MVC Razor engine?

RenderPartial function to render Partial View in ASP.Net MVC Razor. The data will be fetched from database using Entity Framework and then the Partial View will be rendered using the @Html. RenderPartial function in ASP.Net MVC Razor.

How we can render partial view in MVC?

To create a partial view, right-click on view -> shared folder and select Add -> View option. In this way we can add a partial view. It is not mandatory to create a partial view in a shared folder but a partial view is mostly used as a reusable component, it is a good practice to put it in the "shared" folder.

How do I render a partial part of a view?

Rendering a Partial View You can render the partial view in the parent view using the HTML helper methods: @html. Partial() , @html. RenderPartial() , and @html. RenderAction() .


2 Answers

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.

like image 200
Buildstarted Avatar answered Sep 22 '22 06:09

Buildstarted


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

like image 34
Felix Avatar answered Sep 22 '22 06:09

Felix