mvc 大写模型与小写模型 [英] mvc uppercase Model vs lowercase model

查看:23
本文介绍了mvc 大写模型与小写模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个 MVC 5 项目,对 MVC 来说非常新.我注意到代码中的这一行:

I'm working on a MVC 5 project, very new to MVC. I noticed this line in the code:

@Html.DropDownListFor(model => model.ContractorId, Model.Contractors)

页面顶部的指令是:

@model Project.Models.ContractViewModel

ContractViewModel 类中确实有一个 Contractors 对象.

The ContractViewModel class does have a Contractors object in it.

public IEnumerable<SelectListItem> Contractors

我只是对大写的 M (Model.Contractors) 有点困惑,Model 总是指在@model 中传递的对象吗?那么使用Model.Contractors和model.Contractors有什么区别呢?

I'm just a little confused on the capital M (Model.Contractors), does Model always refer to the object passed in the @model? Then what is the difference between using Model.Contractors and model.Contractors?

推荐答案

Model 实际上代表了你的 model 类的一个实例,model 是 lambda 的别名表达.

Model actually represents an instance of the class that is your model and model is an alias for lambda expression.

当您在视图中编写 @Model 时,您使用的是从 Controller 操作传递的 ContractViewModel 对象,如果它不是从 View 传递的,则它可以为 null并且访问 Model 的任何属性都可能抛出 Null Reference Exception 并且编写 Model.Contractors 基本上是指 ContractViewModel.Contractors

When you write @Model in your view you are using the object of ContractViewModel which is passed from Controller action, if it is not passed from View it can be null and accessing any property of Model can throw Null Reference Exception and writing Model.Contractors you basically mean ContractViewModel.Contractors

当你写一个 html helper 时,你需要为它写一个别名,写 model 不是强制性的,你可以写任何东西.

and when you write a html helper you need to write an alias for it, its not mandatory to write model you can write anything.

例如:

@Html.DropDownListFor(m=> m.ContractorId, Model.Contractors)

它只是访问Html Helper中模型属性的别名.

It is just an alias to access the model properties inside Html Helper.

当您在 View 顶部编写 @model Project.Models.ContractViewModel 时,这是另一回事,在这种情况下,我们正在定义将采用 实例的视图模型Project.Models.ContractViewModel ,实际上我们的视图现在被强类型化为 Project.Models.ContractViewModel 类的实例.

When you write @model Project.Models.ContractViewModel at the top of View that is a different thing, in this case we are defining the model of view that it will take instance of Project.Models.ContractViewModel , actually our view is now strongly typed to instance of class Project.Models.ContractViewModel.

这篇关于mvc 大写模型与小写模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆