Reputation: 11
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)
?
Upvotes: 1
Views: 1500
Reputation: 4371
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 a IList<CustomerType>
AND a SelectedCustomerTypeId
property. I just want the second since is the one imma use to create the customer.
Upvotes: 0
Reputation: 4420
Should I rewrite the value in the controller Request.Params ["Name"] to ViewBag.Name and then use it in the view (@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.
@Request.Params["Fake"].ToString()
Of course, you'll have to be careful about ViewBag.Fake
being null as well.
Upvotes: 0
Reputation: 78825
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.
Upvotes: 1