This action attribute will throw 422 - Unprocessable entity in case model was not validated.
<ng-input-text model="someModel" property-name="name" />
<input class="custom-input-text" type="text" ng-disabled="!model.isEditingEnabled" ng-model="model[propertyName]"/>
<small ng-if="validationMessage()" class="error">{{validationMessage()}}</small>
"use strict";
// Taken from here: http://stackoverflow.com/a/18295416/413785
MyApp.Common
.directive("ngInputText", MyAppNgInputTextDirective);
function MyAppNgInputTextDirective() {
return {
restrict: "E",
scope: {
model: "=",
propertyName: "@"
},
controller: MyAppNgInputTextCtrl,
templateUrl: "/app/modules/common/directives/form-elements/input-text.html"
};
}
MyAppNgInputTextCtrl.$inject = ["$scope"];
function MyAppNgInputTextCtrl($scope) {
var modelStatePropertyName = getModelStateProperty($scope.propertyName);
var watchItem = "model." + $scope.propertyName;
// If the value is changed, remove modelState error
$scope.$watch(watchItem, function () {
resetModelState();
});
$scope.validationMessage = function () {
if ($scope.model.modelState && $scope.model.modelState[modelStatePropertyName]) {
return $scope.model.modelState[modelStatePropertyName][0];
}
return "";
}
// Resolves modelState property name for the current model
// (by .net convention it looks something like this: "model.SomeProperty")
function getModelStateProperty(modelStatePropertyName) {
return "model." + modelStatePropertyName.charAt(0).toUpperCase() + modelStatePropertyName.slice(1);
}
function resetModelState() {
if ($scope.model.modelState)
$scope.model.modelState[modelStatePropertyName] = undefined;
}
}
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
namespace SomeNamespace.Web.Infrastructure.Filters
{
/// <summary>
/// This action attribute will throw 422 - Unprocessable entity in case model was not validated.
/// <see href="http://stackoverflow.com/questions/11686690/handle-modelstate-validation-in-asp-net-web-api"/>
/// <seealso href="http://stackoverflow.com/a/3291292/413785"/>
/// </summary>
public class ValidationFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse((HttpStatusCode)422, modelState);
}
//base.OnActionExecuting(actionContext);
}
}
}
[ValidationFilter]
public IHttpActionResult PostMetadataType(MetadataTypeModel model)
{
var type = _metadataService.CreateMetadataType(model.ValueTypeId, model.Name);
model = MetadataTypeMapper.MapToModel(type);
return Ok(model);
}
public class MetadataTypeModel
{
public int Id { get; set; }
[Range(1, int.MaxValue, ErrorMessage = "Value type Id must be greater than 0.")]
public int ValueTypeId { get; set; }
[Required]
public string Name { get; set; }
}