0

What do I do if the input does not qualify to the object model I'm trying to bind to?

for instance, a person has a FirstName and a LastName, so it might have a model binder like:

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var querystrings = controllerContext.HttpContext.Request.QueryString;

        Dictionary<string, string> queryParams = querystrings.Cast<string>()
            .Select(s => new { Key = s, Value = querystrings[s] })
            .ToDictionary(p => p.Key, p => p.Value);

        return new Person
        {
            FirstName = queryParams["firstName"],
            LastName = queryParams["lastName"]
        };
    }

But what if firstName or lastName are not present? how do I signal that i failed to bind?

jajdoo
  • 516
  • 1
  • 9
  • 21
  • 2
    You can do `bindingContext.ModelState.AddModelError("firstName", "Name is required")` then check `ModelState.IsValid`. See [here](http://stackoverflow.com/questions/13684354/validating-a-view-model-after-custom-model-binding) and [here](http://stackoverflow.com/questions/5820637/custom-model-binding-model-state-and-data-annotations). – Jasen Jan 08 '15 at 16:26
  • thanks for the pointing me in the right direction @Jasen – jajdoo Jan 11 '15 at 06:56

0 Answers0