When to use ViewBag, ViewData, or TempData in Mvc3 - asp.net-mvc-3

When to use ViewBag, ViewData, or TempData in view.
In the controller i want to send object to the view.I want to know that which will be best in this case.
I want the object in the view page.

Use TempData when you need data to be available for the next request, only.
TempData["myInfo"] = "my info";
Then in the next request, it will be there... but will be gone after that.
Use ViewBag for most of your extra-data needs to pass to your view, beyond the #model
ViewBag.MyInfo = "my info";
Then access it from your view.
Use ViewData to access/enter the exact same info as ViewBag, except as a collection instead of properties of a dynamic object.
ViewData["MyInfo"]
accesses exactly the same data as ViewBag.MyInfo
Note that I used strings, but these can store any object you wish.
Another thing to note: TempData and ViewData are both dictionaries that store object values, so you must cast those to their original type when you use them. ViewBag however uses dynamic, and you don't always need to cast that, since it is done at runtime. Some methods (like Extension methods) can not handle dynamic though, so you would need to cast in those cases.

IMHO for decent design practies -
ViewBag = never.
ViewData = never.
These are magic string-ish based fields and canot be caught during any compile time instances either.
Your VieWModel should contain everything it needs.
Thats it's purpose in life. Don't devoid it of its purpose. TempData for status messages only or object you don't want to cache but wan't available for the very next request only.

Related

Asp.net mvc Data Model or View Model

I am very new to asp.net mvc techniques, and have a question about how to render a view. In my project, I need to retrieve an XML file(XML string) from database. After getting this XML string, I deserialize xml to an object, say LogMessage, which I have defined already. Once I have got such a LogMessage object, I would like to display its contents to the user via a view. Additionally, I need to process some of the LogMessage properties before showing them to the user. For instance, (1) there is a logTime property in the LogMessage object, which is in utc format and I need to convert it to the local time, (2) there is a logCode property, which is in the format of int number (1,2,3, etc), and I need to convert each number to a meaningful name, such as eventStart, eventEnd, etc.
What in my mind now is that I create a strongly-typed view (of LogMessage type) in asp.net mvc3, so that I can render the view with Razor. Also I put all the necessary functions (e.g., for converting utc time to local time, mapping code number to its meaningful name, etc.) in the same view file, and call them when rendering the view.
But I am not sure whether I should do it as the aforementioned way or I should create another view model, say LogMessageViewModel (as I think actually the LogMessage is my data model or not ?). Then once I have got the LogMessage object, I can create a LogMessageViewModel (and LogMesageViewModel looks quite the same as LogMessage), and initialize the LogMessageViewModel with LogMessage and do all the necessary conversions in my Controller or Model, rather than do them in the View. Then now I have all the correct information in the LogMessageViewModel for the view, and create a strongly-typed view of LogMessageViewModel and simply render a view and show its contents to the user.
Could anyone give me some suggestions about these two different approaches or maybe there are some other better ones?
It is always a good practice to keep the DB layer and the UI layer seperate.
When you are getting data from the DB and storing it in a DataContract(LogMessage in your case), Use automappers to map it to a similar viewmodel(LogMessageViewModel ). Then use the viewModel in the views.
the flow goes like this
DB-> XML values -> LogMessage(DataContract/ Domain Object)-> using
AutoMapper -> LogMessageViewModel-> View
A Razor view engine that is used to render a Web Forms page to the response
Please go to here : ASP.NET MVC View Engine Comparison
That link may help your questions
and refer to : Rendering ASP.NET MVC Razor Views
It is always recommened to use ViewModels , if you require any more information that needs to rendered apart from the information from the model
If any additional processing needs to be done, you can do it in your view model.
Then, you can create a view strongly typed with the view model.
Hopw this helps..
If you are not using models, all the transformation logics , additional data needs to sent to view by using view data.
This makes controller fat.
It is a best practice to maintain your controllers as thin as possible.
Since, considering Single responsibilty principle . The responsibity of controllers is only to make transfer of controls.not any other thing else
**Conclusion: *Recommened to use ViewModel in your scenario***
Hope this helps..

validate data in controller and model, or just controller?

I have the action contlrSaveText() in controller and the method modelSaveText() in model.
When the data comes from the website to the contlrSaveText(), I check whether the required information is received to save text, i.e. text name, text content etc. Then I call modelSaveText() to actually perform saving text. Do I need to validate data in this method as well or I can expect that controlled already did the job?
A model is only an abstract description, while a controller does the work.
Your model might have a controller on its own that take care of the data and updates the model. But that is technically a controller.
How he works with toward the outside, e.g. another controller that fills data in, is up to you how you define the interface. If your model uses relations or properties that require to be set up by the controller then you have to validate the data before inserting/accepting. But if not, then there is no point in validation and it can be skipped for performance reasons.
If you need to reject invalid data you have to think of a way how to tell the outside what whent wrong so it can respond to the error.
In your example I would go for validation, but that is just my opinion.

MVC question: direct modell <-> view communication - why?

can anybody tell me, why communicates the model direct with the view in the MVC pattern, and why not just throught the controller?
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
Sometimes it is too costly to use Controller for simple View/Model communication.
If your view just shows raw data without any operation (filtration, visualization, modification ...) it is easy to forget about Controller.
But this behavior is so abuse-able sometimes it kills all of the advantages of MVC.
And this where MVP comes in:
MVP (Model-View-Presenter) cuts the connection between model and view and every thing pass through man-in-the-middle (Presenter).
The views know of the model and will interact with the model.
If a button is clicked an action message might be sent to a model object in order to get
something done.
If a new value is typed into an entry field an update message might be sent to a model
object in order to give it its new value.
If a value is needed for a display an enquiry message might be sent to a model object in
order to get a value.

MVC - Sanitizing data, where?

I'm using CakePHP but it's a question about the MVC pattern. I have in my form the input-text for the tags (separated by commas). To add the tags I've created a Tag model method that basically check if the tag exists and then add the new tag or just a new unit in the tag counter (the Tag model has these fields: id, name, slug, count).
In the controller I explode the tags field and pass one tag at a time.
The question is: where do I sanitize data? In the controller or in the model method? I think it should be in the controller because that's where I explode but in term of reusability I think I should sanitize data in the model.
What do you think?
You should sanitize your data on the View for client-side and Controller for the server-side.
I would say that, strictly speaking, sanitizing your data should occur in the controller, but sanitizing also generally refers to cleaning user input to avoid many issues, such as SQL injection. Since you're using the term "sanitize" in a different context, we have to pay more attention to what that context is.
You're not cleaning up user input, which means it doesn't really need to happen in the controller. You're changing the result of this action depending on whether or not the item you're saving already exists in the database. Therefore, in my mind, it should be happening in the model (or, as MunkiPhD specified, have a method in some sort of helper class that you can call from anywhere - but I say call it in the model).
Edit: Usually, in MVC, the model knows whether it's supposed to save a new row into the database or update an existing one based on whether or not your model instance has a valid ID. If it has an ID, the model should save to the row indexed by that ID. If it does not, the model creates a new one. It's my understanding that all you want to do is know where to make it decide whether to create a new one or update an existing one, and that happens in the model.
I disagree with sanitizing the data for storage in controller, and think the best place is to do it in model, as controller should not know how the data is stored, but sanitizing needs that knowledge (e.g. mysql_real_escape_string() for storing a MySql vs. pg_escape_string() for PostgresQL, or maybe checking for valid XML if stored in an XML file, or something else for different storage mechanisms).
To prevent things like cross site scripting, do not sanitize the data before storing, as you may have some legitimate use for some html tags later on, and do that (ideally) in view or in controller.
You'd want to sanitize it in from your controller, however, "from" doesn't mean "in." Have a separate class sanitize the data - that way you can call that class from wherever you need to.
You basically want to create the contract that your model will receive good data all the time, which means you'd have to sanitize it beforehand.

mvc 2.0 updatemodel and my ID Column

I have created a create view within my MVC 2.0 Application and by default it included a field for the integer ID Column.
This is definitely a field i do not need.
If i remove the field and use updatemodel when trying to create the object in code, will something break because it doesnt see my ID column data being passed in, even though it is auto increment?
Also, i noticed that in the NerdDinner example, updatemodel was used and after that the repository.save method was called.
I thought that updatemodel would save the object to the database..why then call the .save method afterwards? Or have i missed something?
Any help with this would be appreciated.
Cheers
As I understand it, the UpdateModel method will blow away all data in the object. This is because MVC is round-trip based. Anything that goes out should come back if you need to keep state. See this question for more details.
A better way to handle this scenario in my opinion is to have an input model class as an Action parameter which is passed to a service call to update the domain entity in the DB. (Or this mapping code could be right in the action method if you really want.)
Also please be aware of the security vulnerabilities that could be introduced by binding directly to your DB model.

Resources