Does fluent API IsRequired() does exactly the same as [Required] attribute over the property? - asp.net-core-mvc

If I put [Required] attribue over a property in a model then the <input> helper tag will throw out a validation error if no value is provided, but also it will be affecting database structure.
However does this
modelBuilder.Entity<CartItem>(e =>
{
e.Property(e=>e.Quantity).IsRequired();
}
do the same? Meaning is this causing somehow dynamically adding [Required] attribute to a property so <input> tag helper can notice it?

"Meaning is this causing somehow dynamically adding [Required]
attribute to a property so tag helper can notice it?"
Yes, exactly it is. IsRequired and the [Required] will eventually have the same impact on database schema as it will add a non-nullable constrain on the table column. Means the property would be mandatory. The key difference is we only can use fluent API validation code first's approach while [Required] all approach.
In fact, while using e.Property(e=>e.Quantity).IsRequired() attribute fluent API instead of annotations to get the same client side & server side validation. Rather than use Required. The thing is validation errors thrown based on the Fluent API configurations will not automatically reach the UI, but you can capture it in code and then respond to it accordingly.In addition, you can check the official document here

Related

Disable Grails Scaffolding Validation for one Class

We use the Grails scaffolding for our internal part of our web app. Now we have the requirement to modify some values in the before validate method. The Problem is, that these fields are blank: false or nullable: true
It's no problem to modify these values in the beforeValidate method, but the problem is, that the scaffolding adds a required attribute to the html form, and so we can't submit it with these empty fields.
Is there a way to disable the scaffolding validation on a specific view for a specific class?
Greetings
The short answer is "No, there isn't a way to turn of validation for a specific domain class in scaffolding."
However, you can always generate the views for the domain class and edit the GSPs to remove the required attributes on the fields in question.
grails generate-views com.somewhere.MyDomainClass
Scaffolding is to get you a starting point to work from, not continued use and customization.

What is the ModelState class in MVC 3?

I am learning MVC, and in ASP.Net MVC 3, what is the ModelState class ? I have looked on Google and MSDN, but I can't seem to get a clear understanding of it's purpose. Can anyone help?
Take a look at http://www.gxclarke.org/2010/05/consumption-of-data-in-mvc2-views.html under the ViewData.ModelState section.
The ModelState property is a dictionary object that tracks HTTP values submitted to the server. In addition to storing the name and value of each field, it also tracks associated validation errors. Although its name may suggest otherwise, ModelState isn’t Model-aware. It doesn’t understand what a "Product" is. It simply contains a collection of items with names such as "ProductName" and "UnitPrice". It is the responsibility of other objects—ModelBinders, ViewResult, and the strongly-typed View—to map and interpret ModelState values as Model properties
The ModelState Class in MVC is a class which contains the collection that has the key and values of the data submitted to server in the Post method.When MVC comes across the post it takes all the parameters in the post request and puts them in the instance of a ModelStateDictionary. Whenever the ModelState is active in server,the properties of the model are validated according to the validation attributes that are associated with them. And if any of the property is invalid it will be added to the error list. And the property ModelState.IsValid will be set to false. You can use this later on your code to check if everything is correct.
Refer this link for further information.

MVC 3 How to disable model property validation for float type?

How can I disable the built-in validation for a property of float type?
We have our own custom validation attributes that work fine.
But we have this scenario where we want a float property to accept ( .1 ) as a valid float number. Which obviously means ( 0.1 ), but this number is not accepted by the built-in validation.
Basically I want to disable validation on property-by-property bases and still enforce my own custom validations.
Use a nullable type in your viewmodel property e.g:
float? MyProp {get; set;}
This stops the built in validation from occurring but will still use your custom validation. Obviously as you have now made the property nullable, you may want to put a Required validation attribute on the property to ensure you get a value.
Turns out that .3 is actually accepted by the default model binder. The problem is actually with the client validation implementation. If client validation isn't important to you, you can solve this problem by opening the web.config and changing ClientValidationEnabled to false within AppSettings.

ASP.NET MVC 3 validation order

As part of our ASP.NET MVC3 project, we have implemented some custom validation. On a particular entity e.g. UniqueMandatoryCode, we have got [Required] and our [CustomValidationDataAnnotation].
They both work but I would like to know what is happening under the hood in terms of the order of execution for validation. The issue I have is that our CustomValidation code is hit before the [Required] validation. This poses problems when we pass empty values.
So the question is, how do I control the order of validation i.e. first go through the [Required] validation and then the [CustomValidationDataAnnotation] validation.
I guess the validation order cannot be easily controlled.
The common technique is to ignore the empty/unspecified case in all other validators (ignore = you treat it as valid). You will anyway add a required validator if the value is mandatory that will handle that case. If the value is optional, why would you apply the custom validation rule on an empty/unspecified value?

CompareAttribute and comparing against properties on a complex type

I've just read about MVC3's new CompareAttribute that you can apply to a model's property to define another property that it should match - the classic use case is confirming email address has been entered correctly, or having a Password and ConfirmPassword field. I've run into a problem with trying to implement it in my own project.
We've got a fairly standard User object which, among other things, has these properties:
public class User {
....
[Required, RegularExpression(RegularExpressions.Email, ErrorMessage = "Please supply a valid email address")]
public string EmailAddress
[Required]
public string Password
....
}
I've then incorporated User and a couple of other objects that we need into a view model:
public class SignUpViewModel {
....
public User user { get; set; }
....
}
Which, when passed to the form in the UI, allows the ModelBinder to run the Data Annotation validation for the User object as well as the other objects and primitive types in SignUpViewModel when the user submits the form. I was really pleased when this all "just worked" because it meant that we could define validation in just one place and not have too much work to do in persisting out to the database or map UI models to domain models etc.
Noticing that the Html.EditorFor(model => model.User.Password) emits an with the name set to "User.Password", I added the following to SignUpViewModel:
[Required, Compare("User.Password")]
public string ConfirmPassword { get; set; }
but submitting the form now triggers a validation error along the lines of "Could not find a property named User.Password". I was hoping that it would follow the same kind of convention, but it would appear not :(
I don't really want to put ConfirmPassword into the User object as ConfirmPassword is purely a UI concern, and it seems wrong to have that in a domain object like that. I also don't really want to flatten out the various objects within SignUpViewModel as that starts to feel like duplication of where validation rules are defined, and we're trying to keep our code as DRY as possible.
Has anyone come across a way to get CompareAttribute working with comparing against properties of sibling objects rather than sibling properties as it would appear the attribute expects to?
Get rid of the User property on your SignUpViewModel and put the necessary properties from the User domain object on the SignUpViewModel.
You said you want your concerns separated, and having a domain object as a property on the view model is an example of not having your concerns separated.
This might seem like it could result in your writing more code, but look into a solution like Automapper to automate mapping your domain object properties to view model properties.
Even though smartcaveman's response is great from the architectural standpoint it does not address the original question about inability to leverage CompareAttribute's client-side validation in MVC3 inside models contained within some parent model (complex model). I know of a situation where some reusable [sub]model can be reused from within several parent container models and CompareAttribute is used inside the submodel. The server-side validation in MVC3 will work just fine (when javascript is disabled on the client), but there is a bug in javascript provided by Microsoft that breaks client-side validation. Please follow the link below for the resolution:
MVC3 CompareAttribute Client-side Bug (stackoverflow)
I recently ran into this problem myself; here's how I solved it.
[Compare("OriginalPassword")]
public string ConfirmPassword { get; set; }
public string OriginalPassword
{
get
{
return User.Password;
}
}

Resources