ASP.Net MVC 3 JSON Model Binding and server side model validation mixed with client side validation

前端 未结 3 1959
温柔的废话
温柔的废话 2021-01-31 04:52

I\'ve been playing with the new MVC3 Json Model Binding and it\'s quite nice.

Currently, I can post JSON to controller and bind it. Model Validation occurs nicely too.

3条回答
  •  眼角桃花
    2021-01-31 05:27

    Thanks for this solution. I improved on it a bit by passing a dictionary so that you can use the unobtrusive javascript to put the validation on the individual fields instead of a summary by referencing the key of the dictionary.

        private Dictionary GetModelStateErrorsAsString(ModelStateDictionary state)
        {
            Dictionary errors = new Dictionary();
            foreach (var key in ModelState.Keys)
            {
                var error = ModelState[key].Errors.FirstOrDefault();
                if (error != null)
                {
                    errors.Add(key, error.ErrorMessage);
                }
            }
            return errors;
        }
    

提交回复
热议问题