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

前端 未结 7 1242
日久生厌
日久生厌 2020-12-05 09:28

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

@model dynamic

by using the following code:

@{Html.Re         


        
7条回答
  •  执笔经年
    2020-12-05 09:41

    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 anonymousDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(anonymousObject);
                    IDictionary 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

提交回复
热议问题