asp.net mvc3/razor查看最佳实践
我在视图中使用 (asp mvc3/razor cshtml)
对 Request 对象 的引用(例如,@Request.Params["Name"])
。您认为这是一个非常糟糕的做法吗?我应该将控制器 Request.Params ["Name"]
中的值重写为 ViewBag.Name
,然后在视图 (@ViewBag.Name) 中使用它?
I am using in my views (asp mvc3/razor cshtml)
references to the Request object (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)
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最佳实践是使用模型类。在控制器中创建或更新模型类的实例。然后控制器显示强类型视图。
因此,我会避免从视图直接访问请求以及使用视图包。
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.
是。如果“Name”不存在,您将避免运行时错误。
IDE 不会警告您以下代码将引发
NullReferenceException
。当然,您还必须小心
ViewBag.Fake
是否为 null。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.Of course, you'll have to be careful about
ViewBag.Fake
being null as well.我喜欢使用 viewbag 来存储与模型无关的内容,例如,如果我有一个包含位置的下拉列表。我喜欢只存储模型上所选位置的 ID 和视图包中的位置,因为创建联系人不需要。我认为这就是 viewbag 的目的。
对我来说,模型是业务操作中使用的包或属性,例如,如果我有一个使用 NewCustomerModel 的客户创建视图,我不想用诸如 IList< 之类的东西污染我的模型;CustomerType> 和
SelectedCustomerTypeId
属性。我只想要第二个,因为这是我用来创建客户的一个。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. 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 aIList<CustomerType>
AND aSelectedCustomerTypeId
property. I just want the second since is the one imma use to create the customer.