using ASP.NET MVC, I have a Model, to which I'm attaching attributes so that I can get use the MVC Model bound validation, but to doesn't this break the rule of MVC, where you are putting items that belong to the View, into the Model? I hope I don't come of as trying to be smart, I am however curious as to other's opinions.
public class Payments
{
[DataType(DataType.Text)]
[DisplayFormat(NullDisplayText="")]
[Display(Name="Payment Id")]
[Required(ErrorMessage="Required")]
public int PaymentId { get; set; } //todo: make this into a dropdown
[DataType(DataType.Text)]
[Display(Name="Bill Name")]
[Required(ErrorMessage = "Required")]
public string PaymentName { get; set; }
[DataType(DataType.Date)]
[Display(Name="Date to Post Payment")]
[Required(ErrorMessage = "Required")]
public DateTime PaymentDate { get; set; }
[DataType(DataType.Currency)]
[Range(0, 922337203685477.5807)]
[Required(ErrorMessage = "Required")]
public double PaymentAmount { get; set; }
}
In code we need to check the IsValid property of the ModelState object. If there is a validation error in any of the input fields then the IsValid property is set to false. If all the fields are satisfied then the IsValid property is set to true. Depending upon the value of the property, we need to write the code.
ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .
We can enable and disable the client-side validation by setting the values of ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This setting will be applied to application level. For client-side validation, the values of above both the keys must be true.
Yes. Thats why you should use ViewModels.
You can, but don't have to, put those validation attributes in your model.
But it's better to use a ViewModel:
public class PaymentsViewModel
{
[DataType(DataType.Text)]
[DisplayFormat(NullDisplayText="")]
[Display(Name="Payment Id")]
[Required(ErrorMessage="Required")]
public int PaymentId { get; set; } //todo: make this into a dropdown
[DataType(DataType.Text)]
[Display(Name="Bill Name")]
[Required(ErrorMessage = "Required")]
public string PaymentName { get; set; }
[DataType(DataType.Date)]
[Display(Name="Date to Post Payment")]
[Required(ErrorMessage = "Required")]
public DateTime PaymentDate { get; set; }
[DataType(DataType.Currency)]
[Range(0, 922337203685477.5807)]
[Required(ErrorMessage = "Required")]
public double PaymentAmount { get; set; }
}
And in your View, instead of:
@model YourProject.Models.Payments
you use:
@model YourProject.Models.PaymentsViewModel
for validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With