I've wrote the below code for making appointed date as required field. But when remove the default date and try to submit, no error message is shown.
[DisplayName("Appointed Date")]
[Required(ErrorMessage = "Appointed Date Is Required")]
public virtual DateTime AppointedDate { get; set; }
Please let me know, if i need to do anything more.
Usually this has to do with non-nullable types failing in the model binder on parsing. Make the date nullable in the model and see if that solves your problem. Otherwise, write your own model binder and handle this better.
Edit: And by model I mean a view model for the view, to make the recommended change, if you want to stick with binding to your model in the view (which I am assuming is using EF), follow the write your own model binder suggestion
Edit 2: We did something like this to get a custom format to parse in a nullable datetime (which might be a good start for you to tweak for a non-nullable type):
public sealed class DateTimeBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult);
if (valueProviderResult == null)
{
return null;
}
var attemptedValue = valueProviderResult.AttemptedValue;
return ParseDateTimeInfo(bindingContext, attemptedValue);
}
private static DateTime? ParseDateTimeInfo(ModelBindingContext bindingContext, string attemptedValue)
{
if (string.IsNullOrEmpty(attemptedValue))
{
return null;
}
if (!Regex.IsMatch(attemptedValue, #"^\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}$", RegexOptions.IgnoreCase))
{
var displayName = bindingContext.ModelMetadata.DisplayName;
var errorMessage = string.Format("{0} must be in the format DD-MMM-YYYY", displayName);
bindingContext.ModelState.AddModelError(bindingContext.ModelMetadata.PropertyName, errorMessage);
return null;
}
return DateTime.Parse(attemptedValue);
}
}
Then register this with (by providing this class in your Dependency Injection container):
public class EventOrganizerProviders : IModelBinderProvider
{
public IModelBinder GetBinder(Type modelType)
{
if (modelType == typeof(DateTime))
{
return new DateTimeBinder();
}
// Other types follow
if (modelType == typeof(TimeSpan?))
{
return new TimeSpanBinder();
}
return null;
}
}
Related
How do you call the default model binder within Web API in a custom IModelBinder? I know MVC has a default binder, but I can't use it with Web API. I just want to use the default Web API binder, and then run some custom logic after that (to avoid re-inventing the wheel).
public class CustomBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
// Get default binding (can't mix Web API and MVC)
var defaultMvcBinder = System.Web.ModelBinding.ModelBinders.Binders.DefaultBinder;
var result = defaultMvcBinder.BindModel(actionContext, bindingContext); // Won't work
if (result == false) return false;
// ... set additional model properties
return true;
}
}
In case others stumble on this question, I had to implement the custom model binder with activation context since there is nothing to re-use from Web API. Here is the solution I am using for my limited scenarios that needed to be supported.
Usage
The implementation below allows me to let any model optionally use JsonProperty for model binding, but if not provided, will default to just the property name. It supports mappings from standard .NET types (string, int, double, etc). Not quite production ready, but it meets my use cases so far.
[ModelBinder(typeof(AttributeModelBinder))]
public class PersonModel
{
[JsonProperty("pid")]
public int PersonId { get; set; }
public string Name { get; set; }
}
This allows the following query string to be mapped in a request:
/api/endpoint?pid=1&name=test
Implementation
First, the solution defines a mapped property to track the source property of the model and the target name to use when setting the value from the value provider.
public class MappedProperty
{
public MappedProperty(PropertyInfo source)
{
this.Info = source;
this.Source = source.Name;
this.Target = source.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName ?? source.Name;
}
public PropertyInfo Info { get; }
public string Source { get; }
public string Target { get; }
}
Then, a custom model binder is defined to handle the mapping. It caches the reflected model properties to avoid repeating the reflection on subsequent calls. It may not be quite production ready, but initial testing has been promising.
public class AttributeModelBinder : IModelBinder
{
public static object _lock = new object();
private static Dictionary<Type, IEnumerable<MappedProperty>> _mappings = new Dictionary<Type, IEnumerable<MappedProperty>>();
public IEnumerable<MappedProperty> GetMapping(Type type)
{
if (_mappings.TryGetValue(type, out var result)) return result; // Found
lock (_lock)
{
if (_mappings.TryGetValue(type, out result)) return result; // Check again after lock
return (_mappings[type] = type.GetProperties().Select(p => new MappedProperty(p)));
}
}
public object Convert(Type target, string value)
{
try
{
var converter = TypeDescriptor.GetConverter(target);
if (converter != null)
return converter.ConvertFromString(value);
else
return target.IsValueType ? Activator.CreateInstance(target) : null;
}
catch (NotSupportedException)
{
return target.IsValueType ? Activator.CreateInstance(target) : null;
}
}
public void SetValue(object model, MappedProperty p, IValueProvider valueProvider)
{
var value = valueProvider.GetValue(p.Target)?.AttemptedValue;
if (value == null) return;
p.Info.SetValue(model, this.Convert(p.Info.PropertyType, value));
}
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
try
{
var model = Activator.CreateInstance(bindingContext.ModelType);
var mappings = this.GetMapping(bindingContext.ModelType);
foreach (var p in mappings)
this.SetValue(model, p, bindingContext.ValueProvider);
bindingContext.Model = model;
return true;
}
catch (Exception ex)
{
return false;
}
}
}
I have ASP.NET WebAPI action method that looks like this:
[HttpGet]
public HttpResponseMessage Test([FromUri] TestRequest request)
{
request.Process();
return new HttpResponseMessage(HttpStatusCode.OK);
}
public class TestRequest
{
public string TestParam1 { get; set; }
public string TestParam2 { get; set; }
public void Process()
{
// do work
}
}
This works OK if the request URL has parameters specified, e.g. http://localhost/test?TestParam1=1. But when the query string is empty, request param is null, and I get a NullReferenceException in my method.
Is there a way to tell WebApi to always use an instance of new TestRequest() as a method parameter, even if the query string is empty?
Define a custom model binder:
public class TestRequestModelBinder : System.Web.Http.ModelBinding.IModelBinder
{
public bool BindModel(HttpActionContext actionContext,
System.Web.Http.ModelBinding.ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(TestRequest)) return false;
bindingContext.Model = new TestRequest();
var parameters = actionContext.Request.RequestUri.ParseQueryString();
typeof(TestRequest)
.GetProperties()
.Select(property => property.Name)
.ToList()
.ForEach(propertyName =>
{
var parameterValue = parameters[propertyName];
if(parameterValue == null) return;
typeof(TestRequest).GetProperty(propertyName).SetValue(bindingContext.Model, parameterValue);
});
return bindingContext.ModelState.IsValid;
}
}
Use it:
[HttpGet]
public HttpResponseMessage Test([System.Web.Http.ModelBinding.ModelBinder(typeof(TestRequestModelBinder))] TestRequest request)
{
// your code
}
The answer of Andriy Tolstoy helped, I had to change it a little though to get some of my integer properties to work.
Here is the updated ModelBinder I used, in case it helps someone:
public class TestRequestModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType != typeof(TestRequest)) return false;
bindingContext.Model = new TestRequest();
var parameters = actionContext.Request.RequestUri.ParseQueryString();
typeof(TestRequest)
.GetProperties()
.ToList()
.ForEach(property =>
{
var parameterValue = parameters[property.Name];
if (parameterValue == null) return;
typeof(TestRequest).GetProperty(property.Name).SetValue(bindingContext.Model, Convert.ChangeType(parameterValue, property.PropertyType));
});
return bindingContext.ModelState.IsValid;
}
}
The main change is to cast the value to the property's original PropertyType.
Using Null is the easiest way though not right design wise.
Else you can create custom behavior using a custom model binder for your TestRequest type. You can find loads of examples for the same.
You just need to test for null:
[HttpGet]
public HttpResponseMessage Test([FromUri] TestRequest request)
{
if (request == null)
request = new TestRequest();
var result = request.Process();
It's only possible to set default values to constants in the parameter list so it will not work as you want it to.
If you had a method signature like this you could set the default value to "ok" for example
public HttpResponseMessage Test(string request = "ok")
In your scenario, IMO, the best way is to set the parameter value as nullable and check against that in the controller
[HttpGet]
public HttpResponseMessage Test([FromUri] TestRequest? request)
{
if(request.HasValue)
{
//Do your thing
}
}
I'm trying to use some code that I found on a forum for a better ModelBinder
public class BetterDefaultModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
if (bindingContext.ValueProvider.GetKeys().All(IsRequiredRouteValue))
{
return null;
}
// Notes:
// 1) ContainsPrefix("") == true, for all value providers (even providers with no values)
// 2) ContainsPrefix(null) => ArgumentNullException
if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
{
if (string.IsNullOrEmpty(bindingContext.ModelName) || !bindingContext.FallbackToEmptyPrefix)
{
return null;
}
// We couldn't find any entry that began with the (non-empty) prefix.
// If this is the top-level element, fall back to the empty prefix.
bindingContext = new ModelBindingContext
{
ModelMetadata = bindingContext.ModelMetadata,
ModelState = bindingContext.ModelState,
PropertyFilter = bindingContext.PropertyFilter,
ValueProvider = bindingContext.ValueProvider
};
}
// Simple model = int, string, etc.; determined by calling TypeConverter.CanConvertFrom(typeof(string))
// or by seeing if a value in the request exactly matches the name of the model we're binding.
// Complex type = everything else.
ValueProviderResult vpResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (vpResult != null)
{
return BindSimpleModel(controllerContext, bindingContext, vpResult);
}
return bindingContext.ModelMetadata.IsComplexType ? BindComplexModel(controllerContext, bindingContext) : null;
}
private static bool IsRequiredRouteValue(string value)
{
return new[] { "area", "controller", "action" }.Any(s => value.Equals(s, StringComparison.OrdinalIgnoreCase));
}
}
Within all that code is this block:
if (bindingContext.ValueProvider.GetKeys().All(IsRequiredRouteValue))
{
return null;
}
There's a call in there to a method GetKeys(). I can't figure out where this method comes from, Visual Studio is telling me it doesn't exist. Am I correct in assuming this is an extension method?
Is it simply a using statement that I'm missing? Or is it likely the author of the code created their own GetKeys() extension method and failed to mention it?
I made custom Validator attribute
partial class DataTypeInt : ValidationAttribute
{
public DataTypeInt(string resourceName)
{
base.ErrorMessageResourceType = typeof(blueddPES.Resources.PES.Resource);
base.ErrorMessageResourceName = resourceName;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string number = value.ToString().Trim();
int val;
bool result = int.TryParse(number,out val );
if (result)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("");
}
}
}
But when entered string instead of int value in my textbox then value==null and when i entered int value then value==entered value;. Why?
Is there any alternate by which i can achieve the same (make sure at server side only)
The reason this happens is because the model binder (which runs before any validators) is unable to bind an invalid value to integer. That's why inside your validator you don't get any value. If you want to be able to validate this you could write a custom model binder for the integer type.
Here's how such model binder could look like:
public class IntegerBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
int temp;
if (value == null ||
string.IsNullOrEmpty(value.AttemptedValue) ||
!int.TryParse(value.AttemptedValue, out temp)
)
{
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "invalid integer");
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
return null;
}
return temp;
}
}
and you will register it in Application_Start:
ModelBinders.Binders.Add(typeof(int), new IntegerBinder());
But you might ask: what if I wanted to customize the error message? After all, that's what I was trying to achieve in the first place. What's the point of writing this model binder when the default one already does that for me, it's just that I am unable to customize the error message?
Well, that's pretty easy. You could create a custom attribute which will be used to decorate your view model with and which will contain the error message and inside the model binder you will be able to fetch this error message and use it instead.
So, you could have a dummy validator attribute:
public class MustBeAValidInteger : ValidationAttribute, IMetadataAware
{
public override bool IsValid(object value)
{
return true;
}
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["errorMessage"] = ErrorMessage;
}
}
that you could use to decorate your view model:
[MustBeAValidInteger(ErrorMessage = "The value {0} is not a valid quantity")]
public int Quantity { get; set; }
and adapt the model binder:
public class IntegerBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
int temp;
var attemptedValue = value != null ? value.AttemptedValue : string.Empty;
if (!int.TryParse(attemptedValue, out temp)
)
{
var errorMessage = "{0} is an invalid integer";
if (bindingContext.ModelMetadata.AdditionalValues.ContainsKey("errorMessage"))
{
errorMessage = bindingContext.ModelMetadata.AdditionalValues["errorMessage"] as string;
}
errorMessage = string.Format(errorMessage, attemptedValue);
bindingContext.ModelState.AddModelError(bindingContext.ModelName, errorMessage);
bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);
return null;
}
return temp;
}
}
I made a test website to debug an issue I'm having, and it appears that either I'm passing in the JSON data wrong or MVC just can't bind nullable longs. I'm using the latest MVC 3 release, of course.
public class GetDataModel
{
public string TestString { get; set; }
public long? TestLong { get; set; }
public int? TestInt { get; set; }
}
[HttpPost]
public ActionResult GetData(GetDataModel model)
{
// Do stuff
}
I'm posting a JSON string with the correct JSON content type:
{ "TestString":"test", "TestLong":12345, "TestInt":123 }
The long isn't bound, it's always null. It works if I put the value in quotes, but I shouldn't have to do that, should I? Do I need to have a custom model binder for that value?
I created a testproject just to test this. I put your code into my HomeController and added this to index.cshtml:
<script type="text/javascript">
$(function () {
$.post('Home/GetData', { "TestString": "test", "TestLong": 12345, "TestInt": 123 });
});
</script>
I put a breakpoint in the GetData method, and the values were binded to the model like they should:
So I think there's something wrong with the way you send the values. Are you sure the "TestLong" value is actually sent over the wire? You can check this using Fiddler.
If you don't want to go with Regex and you only care about fixing long?, the following will also fix the problem:
public class JsonModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
{
var propertyType = propertyDescriptor.PropertyType;
if (propertyType.IsGenericType && propertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var provider = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (provider != null
&& provider.RawValue != null
&& Type.GetTypeCode(provider.RawValue.GetType()) == TypeCode.Int32)
{
var value = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize(provider.AttemptedValue, bindingContext.ModelMetadata.ModelType);
return value;
}
}
return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder);
}
}
My colleague came up with a workaround for this. The solution is to take the input stream and use a Regex to wrap all numeric variables in quotes to trick the JavaScriptSerializer into deserialising the longs properly. It's not a perfect solution, but it takes care of the issue.
This is done in a custom model binder. I used Posting JSON Data to ASP.NET MVC as an example. You have to take care, though, if the input stream is accessed anywhere else.
public class JsonModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (!IsJSONRequest(controllerContext))
return base.BindModel(controllerContext, bindingContext);
// Get the JSON data that's been posted
var jsonStringData = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
// Wrap numerics
jsonStringData = Regex.Replace(jsonStringData, #"(?<=:)\s{0,4}(?<num>[\d\.]+)\s{0,4}(?=[,|\]|\}]+)", "\"${num}\"");
// Use the built-in serializer to do the work for us
return new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
}
private static bool IsJSONRequest(ControllerContext controllerContext)
{
var contentType = controllerContext.HttpContext.Request.ContentType;
return contentType.Contains("application/json");
}
}
Then put this in the Global:
ModelBinders.Binders.DefaultBinder = new JsonModelBinder();
Now the long gets bound successfully. I would call this a bug in the JavaScriptSerializer. Also note that arrays of longs or nullable longs get bound just fine without the quotes.
You can use this model binder class
public class LongModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (string.IsNullOrEmpty(valueResult.AttemptedValue))
{
return (long?)null;
}
var modelState = new ModelState { Value = valueResult };
object actualValue = null;
try
{
actualValue = Convert.ToInt64(
valueResult.AttemptedValue,
CultureInfo.InvariantCulture
);
}
catch (FormatException e)
{
modelState.Errors.Add(e);
}
bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
return actualValue;
}
}
In Global.asax Application_Start add these lines
ModelBinders.Binders.Add(typeof(long), new LongModelBinder());
ModelBinders.Binders.Add(typeof(long?), new LongModelBinder());
I wanted to incorporate the solution presented by Edgar but still have the features of the DefaultModelBinder. So instead of creating a new model binder I went with a different approach and replaced the JsonValueProviderFactory with a custom one. There's only a minor change in the code from the original MVC3 source code:
public sealed class NumericJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
{
IDictionary<string, object> d = value as IDictionary<string, object>;
if (d != null)
{
foreach (KeyValuePair<string, object> entry in d)
{
AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
}
return;
}
IList l = value as IList;
if (l != null)
{
for (int i = 0; i < l.Count; i++)
{
AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
}
return;
}
// primitive
backingStore[prefix] = value;
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
{
// not JSON request
return null;
}
StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
string bodyText = reader.ReadToEnd();
if (String.IsNullOrEmpty(bodyText))
{
// no JSON data
return null;
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
// below is the code that Edgar proposed and the only change to original source code
bodyText = Regex.Replace(bodyText, #"(?<=:)\s{0,4}(?<num>[\d\.]+)\s{0,4}(?=[,|\]|\}]+)", "\"${num}\"");
object jsonData = serializer.DeserializeObject(bodyText);
return jsonData;
}
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
{
throw new ArgumentNullException("controllerContext");
}
object jsonData = GetDeserializedObject(controllerContext);
if (jsonData == null)
{
return null;
}
Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
AddToBackingStore(backingStore, String.Empty, jsonData);
return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
}
}
Then to register the new value provider you need to add the following lines to your Global.asax:
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new NumericJsonValueProviderFactory());