0
votes

Is it possible to use [Required] attribute in model, but not in controller.

For example I want to use object in which I will set several parameters, and for the class of this object I want to set attribute [Required].

Is it possible to use logic like ModelState.IsValid or something like it.

Here is an example of code: EmployeeModel employee = this.ToObject(employeeXml);

Employee model has property Name. This property is required. How to verify it?

Regards, Sergey.

2

2 Answers

1
votes

You can use TryUpdateModel method which update ModelState according to model validation rules:

public BranchWizardStep GetNextStep(FormCollection formCollection)
{
    TryUpdateModel(_someModel);

    if (ModelState.IsValid) 
    {
        //...
    }
}

EDIT: But better to use TryValidateModel method which validates model only.

0
votes

add this in your model using System.ComponentModel.DataAnnotations;

and then above yr property add

[Required(ErrorMessage = "This is required")]
[StringLength(100)]

if you also want a display name then add using System.ComponentModel;

and add this above yr property

[DisplayName("Login name")]