Using a generic model in ASP.NET MVC Razor

前端 未结 5 1759
刺人心
刺人心 2020-12-29 01:15

Is it possible to use a generic model in ASP.NET MVC 3 (w/ Razor)? The following fails with a syntax error:

@model DtoViewModel where T : IDto
         


        
5条回答
  •  清酒与你
    2020-12-29 01:42

    Assuming, you want to use a generic type in order to avoid code duplications in each view of ViewModel you can do it this way:

    1. create a view for the parts of ViewModel that are unique to the view

    ModelView.cshtml:

    @model ViewModel
    
    @{Layout = "~/Views/Shared/Layout.cshtml";}
    

    Specific type view

    2. create a view for the common parts, that should be rendered in each view of

    Grid.cshtml:

    @{ var webGrid = new WebGrid(Model.PageItems); }
    
    
    @webGrid.GetHtml("table-striped", mode: WebGridPagerModes.All, firstText: "First", lastText: "Last")

    Since it's a partial view, you don't need to declare the type of Model again. It will simply use the model you defined in the parent view, that renders it. The property IList PageItems of your model, will remain strongly typed with .

    3. Don't forget to actually render the partial view of your common parts

    ModelView.cshtml:

    @RenderPage("~/Views/Shared/Grid.cshtml")
    

提交回复
热议问题