[asp.net-mvc] 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?

This question is related to asp.net-mvc razor asp.net-mvc-3

The answer is


I had the same problem & in my case this is what I did

@Html.Partial("~/Views/Cabinets/_List.cshtml", (List<Shop>)ViewBag.cabinets)

and in Partial view

@foreach (Shop cabinet in Model)
{
    //...
}

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.


Here's a way to pass a dynamic object to a view (or partial view)

Add the following class anywhere in your solution (use System namespace, so its ready to use without having to add any references) -

    namespace System
    {
        public static class ExpandoHelper
        {
            public static ExpandoObject ToExpando(this object anonymousObject)
            {
                IDictionary<string, object> anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
                IDictionary<string, object> expando = new ExpandoObject();
                foreach (var item in anonymousDictionary)
                    expando.Add(item);
                return (ExpandoObject)expando;
            }

        }
    }

When you send the model to the view, convert it to Expando :

    return View(new {x=4, y=6}.ToExpando());

Cheers


Can also be called as

@Html.Partial("_PartialView", (ModelClass)View.Data)

I was playing around with C# code an I accidentally found the solution to your problem haha

This is the code for the Principal view:

`@model dynamic 
 @Html.Partial("_Partial", Model as IDictionary<string, object>)`

Then in the Partial view:

`@model dynamic 
 @if (Model != null) { 
   foreach (var item in Model) 
   { 
    <div>@item.text</div> 
   } 
  }`

It worked for me, I hope this will help you too!!


There's another reason that this can be thrown, even if you're not using dynamic/ExpandoObject. If you are doing a loop, like this:

@foreach (var folder in ViewBag.RootFolder.ChildFolders.ToList())
{
    @Html.Partial("ContentFolderTreeViewItems", folder)
}

In that case, the "var" instead of the type declaration will throw the same error, despite the fact that RootFolder is of type "Folder. By changing the var to the actual type, the problem goes away.

@foreach (ContentFolder folder in ViewBag.RootFolder.ChildFolders.ToList())
{
    @Html.Partial("ContentFolderTreeViewItems", folder)
}

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC