How do you decide on the means of passing model data from asp.net mvc controllers to views? - asp.net

There seem to be multiple means of passing model data from controllers in asp.net mvc to views. Its not clear to me if there's a recommended approach in the mvc v1 and v2 releases or if like most things in life, it depends. I've seen several approaches:
Option 1 - Populate the controller's ViewData dixtionary in either an icky string-based indexing way with casting in the view, or the in a strongly typed way by creating a strongly typed custom model class and passing that via ViewData.
Option 2 - Use ViewData.Model, which I'm not sure I even understand.
Option 3 - Use ViewPage.Model, in which case I'm not sure how you pass the model data from the controller.
I've seen a number of posts poo-pooing options 1 and 2 but I don't understand why. These posts seem to highly recommend 3 in most cases.
How do you approach this? Is there a standard way?

Every view 'should' have a specific model. This is sometimes more work so people use short cuts like ViewData, which works but is just not as clean and type safe in my opinion, so I prefer to have everything in the view's model.
You can then make all your views stongly typed. This is a very clean way to do so. Then in your controller you just call the view like:
YourViewModel model = new YourViewModel()
{
// initialize the data here
};
View(model);
Then in your views you can access all the data via ViewPage Model and it is all type safe and enforced from the controller as well.
EDIT from comments:
You don't need to use ViewData at all if you don't want. You can encapsulate all the data your view needs in a model. Just like the example you quoted with ProductsListViewData. It's just a model that contains all the items that were going to be stored in the ViewData. Both ways work but when you encapsulate it in a class (preferred method where everything is in the model) then all the bits and pieces are strongly typed.
ViewData is a generic container so even though you can just put anything you want into it, it is not type safe and therefore not as 'clean'. It comes down to preference and maintainability. There is only option 1 and 3. Your option 2 is misunderstood and is just option 3 in reality. There is no ViewData.Model just ViewPage.Model.

One approach you may wish to consider as your views become more complex, is to reserve the use of Models for input fields, and use ViewData to support anything else the View needs to render.
There are at least a couple of arguments to support this:
You have a master-page that requires some data to be present (e.g. something like the StackOverflow user information in the header). Applying a site-wide ActionFilter makes it easy to populate this information in ViewData after every action. To put it in model would require that every other Model in the site then inherit from a base Model (this may not seem bad initially, but it can become complicated quickly).
When you are validating a posted form, if there are validation errors you are probably going to want to rebind the model (with the invalid fields) back to the view and display validation messages. This is fine, as data in input fields is posted back and will be bound to the model, but what about any other data your view requires to be re-populated? (e.g. drop-down list values, information messages, etc) These will not be posted back, and it can become messy re-populating these onto the model "around" the posted-back input values. It is often simpler to have a method which populates the ViewData with the..view data.
In my experience I have found this approach works well.
And, in MVC3, the dynamic ViewModels means no more string-indexing!

This might be of some help:
When is it right to use ViewData instead of ViewModels?

(I know the following answer is highly arguable, but it's just the way I like to do it)
I would say use ViewData for simple data-tasks, and use the Model for the main purpose of the View. Check out Rob Conerys ViewData helper-classes here to give them a bit more Strongly typed feel:
http://blog.wekeroad.com/2010/01/20/my-favorite-helpers-for-aspnet-mvc
Using Models for absolubtely everything will bloat your project with hundreds of models just to achieve the smallest thing. I mean if you have a User-setting page, you would normally pass a User-model into the view, but if you decide to show some related data like Customers related to this User. You're stuck with the following solutions
You might have to add a List property to the User-model in order to expose the customers to the view. This leads to the Customer-property always being applied to the User-model everywhere else in the project - or make a new simpler User-model.
Make a new action that returns a partial of customers, which you can use with Html.RenderAction.
OR
you could do ViewData["Customers"] = myRepo.GetCustomersRelatedTo(user); // or something like that.
and (if using Robs helpers) in your view:
<%= Html.RenderPartial("CustomerList", Html.ViewData("Customers")) %>
add a PartialView called CustomerList that takes IEnumerable
In my humble opinion this is a cleaner solution and sure - you end up with a magic string here and there, but I'll stick to this approach until someone shows me a project with not a single magic string.
Use the tools we have in the Framework to get the job done. and Keep it simple s... ;)

Related

Comparison between ViewBag and ViewData? [duplicate]

This question already has answers here:
What's the difference between ViewData and ViewBag?
(17 answers)
Closed 7 years ago.
Which is better to bring data from controller to view in .net MVC amongst ViewBag and ViewData ?
Both the ViewData and ViewBag objects are great for accessing data between the controller and view.
The ViewBag objects lets you add dynamic properties to it which makes it a very verstile tool.So dynamic object, meaning you can add properties to it in the controller.It achieves the same goal as ViewData and should be avoided in favour of using strongly typed view models.
ViewBag is a dynamic wrapper around ViewData.
So with ViewData you can do
ViewData["MyData"] = "Hello World"
You can achieve the same result using
ViewBag.MyData = "Hello World"
Since ViewBag is dynamic, you can access properties that may not actually exist e.g. ViewBag.NothingToSeeHere and the code will still compile. It may hit an exception when you run that line of code, but the property is not resolved until runtime.
More information can be found here
How ViewBag in ASP.NET MVC works
As Jason mentioned, "ViewBag is a dynamic wrapper around ViewData".
For the most part, there isn’t a real technical advantage to choosing one syntax over the other.ViewBag is just syntactic sugar that some people prefer over the dictionary syntax. Although there might not be a technical advantage to choosing one format over the other, there are some critical differences to be aware of between the two syntaxes.
One obvious difference is that ViewBag works only when the key being accessed is a valid C# identifi er. For example, if you place a value in ViewData["Key With Spaces"], you can’t access that value using ViewBag because the code won’t compile.
Another key issue to be aware of is that dynamic values cannot be passed in as parameters to extension methods. The C# compiler must know the real type of every parameter at compile time in order for it to choose the correct extension method.
If any parameter is dynamic, compilation will fail. For example, this code will
always fail: #Html.TextBox("name", ViewBag.Name). To work around this, either use ViewData["Name"] or cast the value to a specifi c type: (string) ViewBag.Name.

ASP.Net MVC - ModelState.AddModelError when GET/POST have different models

I have a use case where I used different models for the GET and POST actions in my controller. This works great for my view, because most of the data goes into labels. The model for the GET method contains 10 properties, but the model for the POST method only needs 3.
This GET view renders a form, which only needs 3 of these properties, not all 10. Thus, the model for the POST method accepts a model class which contains only these 3 properties. Therefore, the ASP.Net MVC model binder populates the model class parameter on my POST method with only these 3 necessary properties, and all is well.
Here's the question: When I encounter some business rule violation in the POST method, and want to use ModelState.AddModelError, and re-display the original view, I no longer have the 7 properties that were not POSTed, as they were not part of the form, and are not part of the model class which this method takes as its parameter.
Currently, I'm calling into a builder to return an instance of the model class for the POST method, and have the GET method itself delegating to the same builder. So, in these cases, when there is some business rule violation in the POST method, I return a View("OriginalGetView", originalGetModel). How can I use ModelState.AddModelError in this case, in the POST method, if I want to send custom messages back to the view, using a completely different model class?
It seemed way too lazy to use the same model class for both the GET and POST methods, given that their needs were so different. What is the best practice here? I see a lot of people recommending to use the same model for both methods, and to POST all of the fields back from hidden form fields, but that just seems like a waste of bandwidth in the majority of cases, and it feels ugly to be sending things like "VendorName" back to the server, when I already have "VendorId".
I may be misunderstanding what you are trying to do, but make sure you aren't being penny-wise and pound foolish. I see you may only want to post the identifiers and not necessarily the descriptors. But it sounds like you have to re-display the view after posting...if so you can just access the model properties if you post the same model that is in the get. If you only post the identifiers, you have to spend time re-accessing the database to get the description values(i.e. vendorname as you describe) using the vendor id no? Wouldn't that also be extra processing? Like I said, I could be misunderstanding your post, but for consistency using the same view model for your view to get and post makes the most sense to me.
Hidden Inputs maybe the best solution here still I think, even on 2g you shouldn't create any lag unless unless the values of your Model properties are long strings or something encrypted or xml.
So your .cshtml would have this in it for the 4 properties not currently included in the form:
<form>
#Html.HiddenFor(m => m.Property1)
#Html.HiddenFor(m => m.Property2)
#Html.HiddenFor(m => m.Property3)
#Html.HiddenFor(m => m.Property4)
But you could also get the model state errors from the original posted model and recreate the ModelError state in your response model to get around using hidden inputs.
I just found this guide (not the answer with Green Checkmark but the highest upped Answer: ASP.NET MVC - How to Preserve ModelState Errors Across RedirectToAction?
Note: if you need to copy model properties from Model to another Model (of the same type or different type), in a cleaner way, check out AutoMapper.
Perhaps this could help with what you were trying to achieve - 'Model' level errors - which wouldn't need to attach to a specific field/property - but can be displayed in a Global area.
https://stackoverflow.com/a/53716648/10257093

Is there a standard way to implement an Edit form for an object that uses collections in ASP.NET MVC2?

Given an extremely simple object with only fields, e.g.:
class Contact {
string firstName;
string lastName;
DateTime birthday;
...
}
When you add a strongly-typed View with view content "Create", you get a nice form with all the fields of your object that passes the form back to the controller, etc, and life is good.
However, when the object becomes slightly more complex, like say we want to store email addresses for Contacts (and of course a Contact can certainly have more than one email address):
class Contact {
string firstName;
string lastName;
DateTime birthday;
ICollection<EmailAddress> emailAddresses;
...
}
Now when you add the strongly-typed view with view Content "Create", you get the same form as before, and the collection is not represented in the form in any way.
So now you have a form which is complete with one exception: you would like to add a section where the user can enter in as many or as few email addresses as they like and have those wrapped up and passed to the Controller on submit.
Is there a standard best-practice way of doing this in ASP.NET MVC2? If so, what is it?
MVC3 handles this a lot better but as your using MVC2 take a look at Steve Sanderson's detailed post on Editing a variable length list, ASP.NET MVC 2-style.
Phil Haack's Model binding to a list also gives you further information on how the default MVC2 model binders handle lists
Well, conceivably you can have your entire view be
HTML.EditorForModel()
If you follow the answer I posted to How to display the content of asp.net cache? to allow the Editor to do a deep dive against your model.
That's not the optimal solution. Manipulating List data in MVC is HARD. Mostly because of years of ASP.NET development has left us so disjoint from the metal of the web that the concepts of editing a list client side is easily lost on us.
For working with lists, you will also most likely need to work with client templating to be able to add new elements and remove elements easily. This can be get very complex due to the fact MVC requires all lists to be indexed and follow numerically otherwise on post backs you will be missing items (aside: I feel this was a terrible design decision)
Now with this being said, I would recommend looking at the KnockoutJS and KnockoutMapping frameworks which with the combination of jQuery and jQuery templating will allow you to create a very rich client experience. This unfortunately will most likely be a very radical departure from your existing development style however I feel what Knockout brings to the table is revolutionary and will open up the web so much further to ASP.NET MVC developers.

In ASP.NET MVC, Data exchange between Model and View is possible?

Is there a option to pass data between Model and view in ASP.NET. If it can be accomplished how? This was asked in an interview !!!
Yes... well, the view is either typed, which means the object that represents the model is directly accessible, or the controller returns a ViewBag with data or anything else the view needs to render. That's the whole point of the model-view part of the pattern.
The whole point of MVC is that the data(Model) should be shown to user (View) by use of Controller. Even if the view is typed, your still need the model to bind to it. Even to create a ViewBag, you need the controller action to fill it...

ASP MVC multi-view form models

I am pretty new to this stuff but I am running into a concept-wall and I keep going back and forth with the best way to handle the problem.
I have a multi-view process to filling out a "New User Form". Each view has a small part of the entire form. In each view I have a model and the model has properties set to an instance of a LINQ to SQL class (for pre-populating) along with dropdown data (state, country). I also thought I should have a model (value object) that represents the entire form. This value object has properties for each LINQ class as well. So I made the view take the value object as a dependency injection. Then what? Just set a property to ViewData to send in multiple models? Seems like a bad idea since I would have to do that to every view. Should all view models come from a base class with the value object?
I might be way off already. Hopefully someone can help me get back on track. The ultimate goal is to have an object that represents the state/data of a form that spans multiple views and the form fields should populate if data is present.
Thanks for your patience!
Okay, so I am going to try to answer my own question but I am still not sure about things. I am going to use the info I got here: http://www.asp.net/Learn/mvc/tutorial-13-cs.aspx to create an instance of the value object that will be available to every view. Then I am sending the instance (or a property of) into the view model through it's constructor.
I am still working on how to keep the instance of the value object through all pages but I am assuming it will have to be done through a session variable of sorts.

Resources