Dynamic view of anonymous type missing member issue - MVC3

前端 未结 6 2031
春和景丽
春和景丽 2021-02-06 17:50

I have an MVC3 site that I\'ve setup for testing another site - most of it has been quick and dirty, and so I\'ve not gone to town creating model and view model types for all th

6条回答
  •  名媛妹妹
    2021-02-06 18:57

    Obviously a 'proper' model type would solve the issue - but let's say I simply don't want to do that because that's my prerogative(!)

    You cannot have such prerogative. Sorry, there is absolutely no excuse for this :-) Not to mention that what you are trying to achieve is impossible because dynamic types are internal to the declaring assembly. Razor views are compiled into a separate dynamic assembly at runtime by the ASP.NET engine.

    So back to the topic: never pass anonymous objects as models to views. Always define use view models. Like this:

    public class MyViewModel
    {
        public int Value { get; set; }
    }
    

    and then:

    public ActionResult Index()
    {
        var model = Enumerable.Range(1, 10).Select(i => new MyViewModel { Value = i });
        return View(model);
    }
    

    and then use a strongly typed view:

    @model IEnumerable
    @Html.DisplayForModel()
    

    and inside the corresponding display template which will automatically be rendered for each element of the collection so that you don't have to write any loops in your views (~/Views/Shared/DisplayTemplates/MyViewModel.cshtml):

    @model MyViewModel
    @:Number: @Html.DisplayFor(x => x.Value)
    

    Things that we have improved from the initial version:

    • We have strongly typed views with Intellisense (and if you activate compilation for views even compile time safety)
    • Usage of strongly typed view models adapted to the specific requirements of your views.
    • Getting rid of ViewBag/ViewData which imply weak typing
    • Usage of display templates which avoid you writing ugly loops in your views => you rely on conventions and the framework does the rest

提交回复
热议问题