Passing a dynamic model in MVC5

I am trying to pass dynamic results to View from Controller, the method is ShowColor

returning dynamic results. In the view, I try to walk through the collection, but I get the error

'object' does not contain a definition for "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

+3


source to share


1 answer


Anonymous object is not the same as dynamic

. If you want to use it like dynamic

, then apply it to this:

@foreach (dynamic m in Model)

      



However, it is best to avoid dynamics if at all possible. You lose all compile time checking and even intellisense. You won't know if you ever waited for a property name before runtime, or even if you accidentally misused the wrong type of thing before runtime. If something is broken, you want to know about it at compile time, not when it already lives and affects users, when you can't even know that an error has occurred unless the user notifies you about it. This is a terrible situation for your application.

Long and short, use strong types. If you want something with properties, ColorID

and ColorName

, create a view model with these properties and select your query in instances of this type. Then everything will be fine and strongly typed, and you will know ahead of time if there is any mistake or problem with your code.

+5


source







All Articles