开发者

ASP.Net MVC: Can I change my mind about having a strongly typed view?

开发者 https://www.devze.com 2023-02-10 02:49 出处:网络
I have some views that did not have a model at the time of creation, meaning that I couldn\'t create them as strongly ty开发者_运维技巧ped views. Now they have models and I would like to change that t

I have some views that did not have a model at the time of creation, meaning that I couldn't create them as strongly ty开发者_运维技巧ped views. Now they have models and I would like to change that to provide intellisense for model properties when writing code in the views. Is there some type of configuration which enables a strongly typed view?


Look at the top of your view. The model declaration should be editable as the first line on the view. If it doesn't have one, here are the approrpriate declarations:

Razor: @model Models.MyModel

ASP.NET:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Models.MyModel>" %>


At the top of your view you will see the type that it uses as a model. Probably right now it says something like 'dynamic'. Compare this to a strongly typed view and you can easily see how to modify.


A view can either be strongly typed to a model in which case you will get strongly typed helpers and the Model property will be bound to this model or the view can be weakly typed in which case you rely on magic strings and no Intellisense at all. If the view wasn't strongly typed when you created it you could modify it and make it strongly typed:

<%@ Page 
    Title="" 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage<AppName.Models.SomeViewModel>" %>

or with the Razor view engine:

@model AppName.Models.SomeViewModel
0

精彩评论

暂无评论...
验证码 换一张
取 消