简体   繁体   English

asp.net mvc3 / razor查看最佳做法

[英]asp.net mvc3 / razor view best practices

I am using in my views (asp mvc3/razor cshtml) references to the Request object (eg, @Request.Params["Name"]) . 我在视图(asp mvc3/razor cshtml)中使用对Request对象的引用(eg, @Request.Params["Name"]) Do you think this is a very bad practice? 您认为这是一个非常不好的做法吗? Should I rewrite the value in the controller Request.Params ["Name"] to ViewBag.Name and then use it in the view (@ViewBag.Name) ? 我应该将控制器Request.Params ["Name"]的值重写为ViewBag.Name ,然后在视图中使用它(@ViewBag.Name)吗?

Best practice is to use a model class. 最佳实践是使用模型类。 An instance of the model class is created or updated in your controller. 将在您的控制器中创建或更新模型类的实例。 Then the controller displays a strongly-typed view. 然后,控制器显示一个强类型的视图。

So I'd avoid direct access to the request from the view as well as the use of the view bag. 因此,我将避免从视图直接访问请求以及使用视图包。

Should I rewrite the value in the controller Request.Params ["Name"] to ViewBag.Name and then use it in the view (@ViewBag.Name)? 我应该将控制器Request.Params [“ Name”]中的值重写为ViewBag.Name,然后在视图中使用它(@ ViewBag.Name)吗?

Yes. 是。 You will avoid runtime errors if "Name" does not exist. 如果“名称”不存在,将避免运行时错误。

The IDE will not warn you of the NullReferenceException about to be thrown with the following code. IDE不会警告您以下代码将引发NullReferenceException

@Request.Params["Fake"].ToString()

Of course, you'll have to be careful about ViewBag.Fake being null as well. 当然,您必须注意ViewBag.Fake为null。

I like to use the viewbag to store things not related to the model, for example if I have a dropdown containing locations. 我喜欢使用视图包来存储与模型无关的内容,例如,如果我有一个包含位置的下拉列表。 I like to store only the id of the selected location on the model and the locations in the viewbag, since is not needed to create a contact. 我只想存储模型上所选位置的ID和视图包中的位置,因为不需要创建联系人。 I think that's the purpose of the viewbag. 我认为这就是提包的目的。

For me the model is a bag or properties used in business operations, for example if I have a customer creation view using a NewCustomerModel , I don't wanna pollute my model with things like a IList<CustomerType> AND a SelectedCustomerTypeId property. 对我来说,模型是业务操作中使用的包或属性,例如,如果我有一个使用NewCustomerModel的客户创建视图,那么我就不想用IList<CustomerType>SelectedCustomerTypeId属性之类的东西来污染我的模型。 I just want the second since is the one imma use to create the customer. 我只想第二个,因为这是创建客户的一种imma用法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM