When to check and when not to check ModelState.IsValid - c#

I'm using ASP.NET MVC2.
I love how I can annotate my model's fields and check ModelState.IsValid.
The obvious reason to check it is when doing validation, but should you always check it in case new validation rules are applied to the model?
That way you don't forget / need to check whether the controller checks IsValid.
Is there some reason not to do this check in all cases? Maybe just when the controller action has side-effects (DB-writing etc)?

but should you always check it in case new validation rules are
applied to the model?
You should do this check always else you end up persisting models that don't have valid state.

Generally, in asp.net-mvc, models passed to actions are view models, and they contain all and only data needed for action to act. If that data is invalid, theoretically it should be impossible for action to do its job.
ModelState.IsValid ensures that all data needed for action is in good state, ready to be acted on. I do not see reason where you would not want to validate that data.

You should always check if the model is valid immediately before attempting to use the data collected in the model to do something. That's the purpose of validation in the first place.

It looks obvious to mention, but i will give it a shot.
There is NO need to check model state when you are NOT posting your model. The common scenarios are when you are getting your data from service and displaying on a get action.

Related

How to validate all properties in a model at the same time?

I have a Blazor application. In this application I have several models with various ValidationAttributes.
To validate these models I use an EditForm from Microsoft.AspNetCore.Components.Forms. On this form there is a parameter Called EditContext where I call the Validate() method to validate my models.
The validation itself works fine. However the order of when validations are run seems to be based on the type, like this:
Required
Other(Like Range)
IValidatableObject
This results in Required validations being validated first and only after these are valid in the model the other validations are running.
What I want is for all validations to run at the same time.
Does anyone know how to achieve this in Blazor?
Thanks
What I want is for all validations to run at the same time.
Not sure what you mean? All registered validations are run when you call Validate. There's has to be a sequence. If you want to change the sequence then you need to write your own validator.
the order of when validations are run seems to be based on the type
Validate on the edit context looks like this. It simply invokes any delegates registered with the OnValidationRequested event.
public event EventHandler<ValidationRequestedEventArgs>? OnValidationRequested;
public bool Validate()
{
OnValidationRequested?.Invoke(this, ValidationRequestedEventArgs.Empty);
return !GetValidationMessages().Any();
}
DataAnnotationsValidator or whatever validator you use registers a handler on this event.
In your case the validator is finding fields to validate by searching through the properties in the Model (referenced in EditContext) for specifc attributes. The first attribute it looks for is Required, ....
I'm apparently not allowed to write comments - only answers - but you're right and what Shaun Curtis says is definitely wrong. For anybody doubting this there's a gist here.
When using <DataAnnotationsValidator /> the validation attributes on the model are processed first - only once all of the attribute validation rules pass will the IValidatableObject.Validate method be called.
The functionality is by design - IValidatableObject is to validate the entire object once all of its properties have been filled out. Why is IValidatableObject.Validate only called if property validation passes?
I think Required validation is checked first for a reason. All subsequent validations can and must be run only after the property has a value.
Otherwise, all the other validations would fail by default. It's the framework just reminding you that you forgot to type in a field. After you supply the value, then it goes on to validate its format and what not.
I hope that makes sense.

Model Binding vs Form Collection, performance, scalability, change, etc.? [duplicate]

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 ;)

Required for model but initially empty field for View - MVVM

please help me with this:
I have model with property of Enum type. This property is required, but on View initial value must be empty. Will show watermark..
If I understand correct than model will have not nullable property. But viewModel will have nullable. Is this right way?
Looks like in this case:
need create viewModel
viewModel and model will have different data sometimes
viewModel need logic for set and get correct values to/from model or get null in first time and leave as is model
viewModel need one more validation rule
Other way is:
Model will have nullable property and required validation:
can bind to model
model does not "correspond to reality"
we need always expose data from nullable enum and forgot about null? or handle it (convert to DTO or something like this)
nullable property is only UI requirement and can be changed in future
Having the (domain) model use a non-nullable enum suggest that the value MUST have a valid value for use case and / or data integrity.
Having the requirement on the UI to allow a non-valid value (initial or otherwise) will result in 1 of 2 things:
When the View posts a null value (via a dedicated ViewModel) and checks are performed to ensure its not null (I assume that the user selects the "Please Select" value from a select box) the server will respond with an error message saying something like "Please select a valid value blah blah".
Or, the server will allow the null from the View Model and default the domain model property to some predetermined sensible value.
In my experience this kind of setup leads to a frustrating user experience because having the UI present an invalid selection option that only feedsback upon submit (or using some frontend / client validation) is rather annoying (especially on a long form, Etc).
Perhaps you would be better rethinking that requirement so the UI only presents valid enum values for selection and optionally make the default one a sensible value.
Having said that if you really want the UI to not have a valid initial value then make a view model with a nullable version and validate on the server as you suggest. As far as changing the (domain) model with a nullable, you already seem concerned that it doesn't "correspond to reality" which is a good impulse considering you already mentioned that this is a UI only requirement, thus place the detail in that layer and keep your domain modals as close to reality as is needed to satisfy your use cases and / or business requirements.

Bypass server-side model validation dynamically ASP.NET MVC

I am now working on an existing asp.net MVC application which has a few submit button in one web page(e.g. ignore, delete, update, submit...) And they all send a post request to the server and the server will perform different operation based on the request action type (e.g. ignore, delete, update, submit).
However, an issue is raised that the model validation will always triggered regardless of the operation. According to the business rule, we only need to perform validation for some certain operations. I can clear the error in the modelstate after the validation. (for example MVC3 Remove ModelState Errors).
However I am hoping there is a better way to just bypass the model validation according to the operation parameter from the client.
BTW: I am not allowed to significantly change the way how it works (e.g. send to another action for those operation that does not care about the validation), so I am hoping there is some trick that I can use to achieve this easily.
I assume now you are checking model state errors like...
if (ModelState.Valid)
{... valid and do something...}
If so, you can include some additional checking before hand that will be considered in your conditional. For instance, if it is a delete submit, you can check that before hand.
bool isDelete = ***check some value***
if (isDelete || ModelState.Valid)
{... valid and do something...}
This way even if the model state is invalid, it will still move forward.
One thing to consider is you will need to set something in the model to tell you what action is happening. This probably means using javascript to capture the submit, set a model field, and then perform the submit.

How to know whether a model is feasible

I am using C# api. Given a gurobi model
GRBModel model = new GRBModel(env);
after populating constraint, giving objective function, and doing
model.Optimize();
is there a way to determine whether the model is feasible?
You need to check the optimization status code after solving the model. In most cases, you simply need to test that the status is OPTIMAL. For an example, see mip2_cs.cs in the examples\c# subdirectory.

Categories