0

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.

4

2 回答 2

1

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.

于 2012-06-27T10:40:13.663 回答
0

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")]
于 2012-06-27T10:33:34.067 回答