Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

When I try to render a partial view whose model type is specified as:

@model dynamic

by using the following code:

@{Html.RenderPartial("PartialView", Model.UserProfile);}

I get the following exception:

'System.Web.Mvc.HtmlHelper<dynamic>' has no applicable method named 'RenderPartial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

However, the same code in a .aspx file works flawlessly. Any thoughts?

like image 951
Diego Avatar asked Oct 28 '10 22:10

Diego


People also ask

Which is the way to render partial view using ASP.NET 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 do you render a partial view inside a view in MVC?

Partial function which renders the Partial View. The name of the View and the object of the CustomerModel class are passed to the @Html. Partial function. In order to add Partial View, you will need to Right Click inside the Controller class and click on the Add View option in order to create a View for the Controller.


3 Answers

Just found the answer, it appears that the view where I was placing the RenderPartial code had a dynamic model, and thus, MVC couldn't choose the correct method to use. Casting the model in the RenderPartial call to the correct type fixed the issue.

source: Using Html.RenderPartial() in ascx files

like image 72
Diego Avatar answered Sep 23 '22 20:09

Diego


Instead of casting the model in the RenderPartial call, and since you're using razor, you can modify the first line in your view from

@model dynamic

to

@model YourNamespace.YourModelType

This has the advantage of working on every @Html.Partial call you have in the view, and also gives you intellisense for the properties.

like image 26
juan Avatar answered Sep 21 '22 20:09

juan


Can also be called as

@Html.Partial("_PartialView", (ModelClass)View.Data)
like image 18
Tom Avatar answered Sep 25 '22 20:09

Tom