asp.net-mvc 在 MVC5 Razor View 中传递动态模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27363711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:20:25  来源:igfitidea点击:

passing dynamic model in MVC5 Razor View

asp.net-mvcrazordynamicviewasp.net-mvc-5

提问by sairfan

I'm trying to pass dynamic results to View from Controller, method ShowColorreturns dynamic results. In View I try to loop through the collection but I'm getting error

我正在尝试将动态结果从 Controller 传递给 View,方法ShowColor返回动态结果。在视图中,我尝试遍历集合,但出现错误

'object' does not contain a definition for 'ColorID'.

“object”不包含“ColorID”的定义。

I have the following code in Controller and View

我在控制器和视图中有以下代码

public class myColor
{
    public int ID { get; set; }
    public string  Name { get; set; }
    public string Like { get; set; }
}

public dynamic ShowColor()
{
    IList<myColor> color = new List<myColor>();
    color.Add(new myColor { ID = 1, Name = "Red", Like = "***" });
    color.Add(new myColor { ID = 2, Name = "Green", Like = "*****" });
    color.Add(new myColor { ID = 3, Name = "Blue", Like = "**" });
    color.Add(new myColor { ID = 4, Name = "Yellow", Like = "*" });

    var select = (from c in color
                  select new
                  {                     
                      ColorID = c.ID,
                      ColorName = c.Name
                  }).ToList();

    return select;
}
public ActionResult DBDynamic()
{
    return View(ShowColor());
}

View

看法

@model dynamic

@{
    ViewBag.Title = "DBDynamic";
}

<h2>DBDynamic</h2>

<p>
    <ul>
        @foreach (var m in Model)
        {
            <li> @m.ColorID</li>            
        }
    </ul>

</p>

Error

错误

Debug Image

调试图像

Found the solutionhereand a nice blog here:

找到了解决办法在这里和一个不错的博客在这里

public static ExpandoObject ToExpando(this object anonymousObject)
{
    IDictionary<string, object> expando = new ExpandoObject();
    foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(anonymousObject))
    {
        var obj = propertyDescriptor.GetValue(anonymousObject);
        expando.Add(propertyDescriptor.Name, obj);
    }

    return (ExpandoObject)expando;
}

And call it like this

并这样称呼它

    var select = (from c in color
                select new
                {
                    ColorID = c.ID,
                    ColorName = c.Name
                })
                .AsEnumerable()
                .Select(x => x.ToExpando());

return View(select);

回答by Chris Pratt

An anonymous object is not the same thing as a dynamic. If you want to use it like a dynamicthen cast it to that:

匿名对象与dynamic. 如果您想像 a 一样使用它,dynamic则将其转换为:

@foreach (dynamic m in Model)

However, dynamics are best avoided if at all possible. You lose all compile-time checking and even intellisense. You won't know if you fat-fingered a property name until runtime or even if you've accidentally used the wrong type of thing the wrong way until runtime. If something is broken, you want to know about it at compile-time, not when it's already live and affecting users, when you may not even know that an error has occurred unless a user notifies you. That's a horrible situation for your app to be in.

然而,如果可能的话,最好避免动态。您将丢失所有编译时检查甚至智能感知。直到运行时,您都不知道是否对属性名称进行了粗指处理,或者即使在运行时之前您不小心以错误的方式使用了错误类型的事物。如果某个东西坏了,你想在编译时知道它,而不是当它已经存在并影响用户时,除非用户通知你,否则你甚至可能不知道发生了错误。对于您的应用程序来说,这是一个可怕的情况。

Long and short, use strong types. If you want something with properties, ColorIDand ColorName, create a view model with those properties and select your query into instances of that type. Then, everything will be nice and strongly-typed and you'll know well in advance if there's some error or problem with your code.

多头和空头,使用强类型。如果你想要一些带有属性的东西,ColorIDColorName,用这些属性创建一个视图模型,然后选择你的查询到该类型的实例中。然后,一切都会很好并且是强类型的,如果您的代码存在一些错误或问题,您将提前知道。