I've inherited a code base written in ASP.Net MVC 4. Every post method takes a FormCollection. Aside from annoyance of having to access the values through quoted strings, it also leads to drawbacks such as not being able to use things like ModelState.IsValid, or [AllowHtml] attributes on my ViewModel properties. They actually did create ViewModel classes for each of their views, (though they are pretty much just direct wrappers around the actual Entity Framework Model classes), but they are only used for the GET methods.
Is there anything I'm missing about FormCollection that gives a reason why this may have actually been a good idea? It seems to only have drawbacks. I'd like to go through and "fix" it by using ViewModels instead. This would take a good bit of work because the ViewModels have properties that are interfaces and not concrete classes, which means either writing a custom binder or changing the ViewModels.
But perhaps there's something I'm missing where it makes sense to use FormCollection?
Is there any good reason to use FormCollection instead of ViewModel?
No. I have following issues.
Issue - 1
In case FormCollection is being used...It will be mandatory to Type Cast the Primitive Type Values un-necessarily because while getting the entry of specific Index of the System.Collections.Specialized.NameValueCollection, value being returned is of type String. This situation will not come in case of Strongly Typed View-Models.
Issue - 2
When you submit the form and goes to Post Action Method, and View-Model as Parameter exists in the Action method, you have the provision to send back the Posted Values to you View. Otherwise, write the code again to send back via TempData/ViewData/ViewBag
View-Models are normal classes, created to bind data to-from Views
Issue - 3
We have Data Annotations that can be implemented in View Model or Custom Validations.
ASP.Net MVC simplifies model validatons using Data Annotation. Data Annotations are attributes thyat are applied over properties. We can create custom validation Attribute by inheriting the built-in Validation Attribute class.
Issue - 4
Example you have the following HTML
<input type="text" name="textBox1" value="harsha" customAttr1 = "MyValue" />
Question : How can we access the value of customAttr1 from the above eg from inside the controller
Answer : When a form get posted only the name and value of elements are posted back to the server.
Alternatives : Use a bit of jQuery to get the custom attribute values, and post that along with the form values to action method
Another option is to rather put what you got in your custom attributes in hidden controls
That's the reason, I would always prefer to use View-Models
The only advantage I can think of is if you want to use the automatically generated controller provided when you don't specify a EF model to be strongly typed to. In that case, your Create and Edit actions will use the FormCollection object as it is a reliable, pre-existing artifact of the framework to work with for this purpose. Perhaps the previous developer chose this option while creating his controllers, and stuck with it since Visual Studio must know what it's doing :)
But, in reality, I would never recommend this headstart of a few seconds. It's always better to build out viewmodels, I would recommend looking at the effort to move in that direction if only for maintenance purposes. With model binding and strongly typed views and html helpers, you are much more likely to reduce the number of run-time errors as a result of changing some magic string and not realizing it until your page blows up.
Ok, I see the general consensus here is that it isn't liked. To offer another perspective, I've always liked using the formcollection passed into the controller on POST actions. It offers the use of the TryUpdateModel method from the controller which will map the collection to your strongly typed class. TryUpdateModel also has overloads that allow you to white list the properties of the model that you want to allow to be updated.
if (TryUpdateModel(viewModel, new string[] { "Name" }))
{
//Do something
}
It still allows all the model binding you want, but helps to keep anything other than the "Name" property on my viewmodel from being updated.
You can see more about the TryUpdateModel method here:
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.tryupdatemodel(v=vs.108).aspx
There are always workarounds for getting away from a FormCollection lol.. you can have hidden fields bound to your view model variables in the form to your heart's content.
Form collections mostly emerge from the laziness of creating a view model but still end up taking time trying to get figure out how to get the values out of it in your controller :P
I think it was simply created in the very beginning of MVC as an alternative to using strongly typed views when having very simple forms - back in the days when everyone used ViewBag :) ... and once hey had it in there they couldn't just take it out as simple as that.
Maybe you can use it if you are absolutely sure your view will never have more than one form input? Probably still a bad idea though..
I cant find any recent articles talking about any advantages of form collections.. while strongly typed views are everywhere.
Yes. Sometimes, it can be useful. Here's an example:
Let's say we have in our db "date_and_time_field".
In Razor View, we want to use two form fields. The first one "Date" (maybe with jQuery UI Datepicker). The second one "Hour".
In the Controller Action, we compose the "date_and_time_field" by means of Request.Form["Date"] and Request.Form["Hour"].
There are other scenarios where it can be useful:
A cross-table (with checkBoxes in Razor view)
The collection Request.Unvalidated().Form (maybe this is not part of your question: I don't wanna be off-topic)
The default model binder will do almost everything you need it to do. I resorted to the FormCollection once - only to later figure out how to bind arrays of elements into a collection on the ViewModel.
Just go ViewModel. Better all around, for every reason enumerated.
With form collection you will be able to get all the values inside the form. There can be situations where you may need to pass some additional values from the form which may not be part of your view model.
Just take an example of passing 10 hidden values from the form. The form collection makes sense.
The only difficulty that you may face is type casting. All form collection items that you get will be string; you may need to type cast based on your requirement.
Also model state validation is another area where you may face a challenge.
You can always add the form collection properties to your method signatures. They will automatically be populated by form values with corresponding keys.
Well with Forms Collection you will find a quick way to get the values of a form. Otherwise you have to create a class that mimics the Form Fields and people are sometime lazy to create custom classes for less important/rarely used Forms.
No there is no extra benefit (in fact limited) of forms collection over a custom class as action parameters and it should be avoided whenever possible.
Responding to the title question: yes.
There are some situations that FormCollection needs to be used. For instance, suppose a ViewModel that has a property that implements the 1 to N relation (in concrete case, a TimesheetViewModel with ICollection<TimesheetEntryViewModel>), and the Controller has to perform a validation between the time entries to not get a time collision between the end time of an entry and the start time of the following entry. To mark a related entry with a validation error, how can be the line index be retrieved?
Well, with the default model binding, the index value is lost in the Controller logic. Fortunately, FormController stores the index you used in the View and a more specific validation can be done.
There are type of SPA apps where you have no idea about your model (there is no ViewModel at all and views are created dynamically (for short ;))), so FormCollection is your only choice where you implement custom post validation having entire page input values...
If your view has a knowledge about the model then, of course, you can use your concrete ViewModel object. That's easy ;)
I am developing a Web-App using ASP.NET MVC and I've been trying to avoid using the ViewBag, therefore I created few viewmodels to populate my drop-downs and in general to pass the data I need in my views. At the same time I would like to keep the data binding clean and avoid properties that will not be bound to (without using include/exclude attributes) and I've been told that obviously returnmodels are great for that purpose.
So is creating two independent models for one view a bad idea? One with all the data that needs to be displayed and another one only with the fields from my form or is this an excess of form over substance and should I reconsider changing my design?
Edit: A quick example because I'm not too good at explaining
class ViewModelA{ // passed to the view and then bound to when form is submitted
List<KeyValuePair<int, string>> DropDownValues; // will be always empty while databinding
int SelectedValue; // will be always 0 when passed to the view
...
}
Should I replace ViewModelA with
class ViewModelB{ // contains data passed to the view
List<KeyValuePair<int, string>> DropDownValues;
...
}
class ReturnModel{ // contains data returned from the view
int SelectedValue;
...
}
Obviously here I could just bind directly to my model but let's assume it's more complex and the data has to be processed before saved.
I think I know what you are asking. You are saying you have a viewmodel with, lets say, these properties: Age, Name, CountryOfResidence (for dropdown), and a few more properties. But when you create a new person, you only post Age, Name, IdOfCountry to controller.
So your question is what is the point of posting the whole viewmodel, when it is not needed. Fair question.
There are many ways you can do this. Here is one way:
Create a base class with common properties (for posting)
Create a derived class with more properties for the view.
Some people will refer to 1 as Data Transfer Object (DTO). These DTO's will be shared for communication between presentation layer, service layer, business layer, data access layer etc.
I would like to create a more complex EditorTemplate to select a customer from a list.
I'm aware of the DropDownListFor, but I would like to show cards with customer
pictures and some data not just a regular select list.
What I would like to do:
create an EditorTemplate for customer selecting, for instance... In any POCO Class
public class X{
[Key] int Id {get;set;}
[UIHint("CustomerSelector")] int Custumer_Id {get;set;}
}
And the "CustomerSelector" Editor template be able to query all clients and show them into a rich list.
What is the problem:
It's not a good idea to add querying logic from inside a view. This is against MVC pattern.
It's not very modular to query the customer list in every controller and pass it as argument to the EditorTemplate.
How can I create this EditorTemplate without mess up with the MVC pattern nor duplicate code in every controller?
Unfortunately, there is no truly good way to handle something like this. Your are correct that it's improper for database access to happen within a view. Not only does this violate MVC, but it would also require creating an additional instance of your context in the view, when you should really have just one per request.
The alternative, as you've mentioned, would be to do the query in the controller and then pass that into your view. Honestly, this is probably your best of bad options here.
Another choice I see is to use a child action. A child action allows you to confine the logic of querying the users and passing to a view in just one place. The downside is that that you would have to handle the field naming manually, because the rendering of the child actions view will be outside the scope of the form you're building. In other words, you'd have to do something like:
#Html.Action("CustomerSelect", new { fieldName = "Customer_Id" })
That's not really ideal, either, as now you've got a string that you've got to keep track of, and you'll have to be careful about actually providing the right name. For example, if this was a collection of items, then you'd actually need to pass something like "MyCollection[" + i.ToString() + "].Customer_Id". You can see that this starts to get messy quick. For this reason alone, I'd pretty much nix this as a possible solution.
One final option is to use an HtmlHelper extension. This has the same problem as an editor template would in that you're going to have to new up an instance of your context, but it's at least better in the respect that it's not being done inside a Razor view.
I have an MVC 5 project and part of that is a registration. Presently the form submits using the standard form submit action and my model binder does its job gloriously and all is good.
However, I now need to add a dynamic element to my form such that a user needs to be able to add on the fly invitations to add team members via a textbox for an email address and a dropdown list for that team members role... and an add another button to add another textbox and dropdown list for the next team member... and the next... ad infinitum...
Upon form submission, my model binder is going to fall over and not know what to do with these dynamic elements, so I need suggestions for how to get my model binder to deserialize these items into an array of email & role (role binds to an enum).
I've had it suggested that client side script can catch the submission and serialize the items to a text string and put that in a hidden form field that I can then deserialize manually on my controller action, which seems like it'll work okay, but it feels dirty.
What is the most straightforward way of achieving this? Is there anything built into .NET that will automatically handle this somehow if I configure my view correctly?
Your model can store your "dynamic" fields in a collection like:
public List<string> Emails { get; set; }
In your view you just create subsequent indexed names (exact naming depends on how you're generating this new fields):
model.Emails[0] // name="Emails[0]"
model.Emails[1] // name="Emails[1]"
In your controller action, there should be nothing special the model binder has to do. It will easily be able to handle the collections.
There is an old article from Phil Haack about binding to a List:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/
I guess you could add a ICollection<Invitation>-Property to your model and set the Name of the form fields as explained in the article.
Although personally I would bind the data to a JavaScript-ViewModel and post JSON back to the Server using Ajax.
Upon clicking the "Add more" button, simply inject the textbox and dropdown and let the form serialize like usual.
On the server, accept a list of invitations:
public class Invitation
{
public string EmailAddresss {get; set;}
public int InvitationType {get; set; }
}
public ActionResult Register(MyCurrentModel dto, Invitation[] invitations)
{
//..
}
I'm building a driver's application for employment and I'd like the list of 'accidents' to be dynamic in the sense of only one field appears, but they can add however many they need and once added they appear in a table above the input..
I'm trying to find out what the best way to do this is in a MVC3 Form that is using Razor syntax?
Model has a declaration similar to...
public class FormModel {
...other properties
public IEnumerable<AccidentDetail> AccidentDetails { get; set; }
...other properties
}
This is very much shortened, but wanted to ensure that I was declaring it properly in the model and then I need to know how it's generally handled in the Form to do something like this. I can't make any assumptions to the existence of an accident or the limit of how many they may have.
I personally would approach this with some JavaScript. In particular, I'd use jQuery to add a new field to the table when a button is clicked to "Add another accident". You can use jQuery to grab the values of the fields into an array. The array of accidents would be serialized to json and stored in a hidden field on the form that would be submitted to the server. In your controller you could deserialize that string of json to your strong type. On the server side I've used Json.NET with great success. On the client side you can use Doug Crockford's json2.js. Feel free to email me if you need a little bigger push in the right direction.