How to send model with validation from web api 2 c#

I am working on Asp.net WebApi2 and I want to send Model + validation to client.because then with validation client application can put those validations.

I can validate data sent by client application by creating class

public class CalibrationEntity : BaseEntity
{
    [Required(AllowEmptyStrings = false)]        
    [RegularExpression(@"\d{0,3}", ErrorMessage = "The calno field must be in format XXX")]
    public string calno { get; set; }

    [Required(AllowEmptyStrings = false)]
    [DataType(DataType.DateTime)]        
    public Nullable<System.DateTime> dte_createdon { get; set; }

    [StringLength(10)]        
    public string equip_mode { get; set; } 
}

I can use above class to validate data sent by client application to API but How can can I sent Model and validations to client ??

Answers


You can return a HTTP 400 BadRequest together with the ModelState.

    [Authorize(Roles = "Admin, Secretary")]
    [HttpPost]
    [ActionName("Create")]
    public IHttpActionResult PostCreate(SalesOrderRequestModel request)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }            

        return Ok();
    }

This will make the API return a response like:

{"Message":"The request is invalid.","ModelState":{"model.Email":["Email is required."],"model.FirstName"
:["First name must be 2-30 characters in length.","First name is required."],"model.LastName":["Last
 name must be 2-30 characters in length.","Last name is required."],"model.CountryCode":["Country is
 required."],"model.Address1":["Address must be 5-150 characters in length.","Address is required."]
,"model.Role":["Role is required."]}}

If you are using JavaScript here is a code that populates an array with the ModelState errors.

function getModelState(data) {

    var errors = [];
    if (data != undefined) {
        for (var key in data.ModelState) {
            for (var i = 0; i < data.ModelState[key].length; i++) {
                errors.push(data.ModelState[key][i]);
            }
        }
    }

    return errors;

};

You can now pass the entire response from the API to this function and it will return a string array containing all the validation errors.


Need Your Help

Finding undefined symbols in windows static lib

c windows static-libraries

Is there any way to find out the list of undefined symbols in windows static library compiled using VC6?

There is no property with name 'restriction_class_id' defined in type referred by Role 'phones_extensions'

entity-framework entity-framework-4

I created a new Entity Framework model from a database. This database has a number of tables, the main table is phones_extensions. The phones_extensions table has columns which are FK's to the other