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

前端 未结 3 1835
温柔的废话
温柔的废话 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:44

    The following example works for me when using unobtrusive JavaScript in MVC3. I'm doing something very similar. Given the following JsonResponse class:

    public enum Status
    {
        Ok,
        Error
    }
    
    public class JsonResponse
    {
        public Status Status { get; set; }
        public string Message { get; set; }
        public List Errors { get; set; }
    }
    

    My controller can have a method thus:

    [HttpPost]
    public ActionResult Login(UserLoginModel model)
    {
        JsonResponse res = new JsonResponse();
    
        if (!ModelState.IsValid)
        {
            res.Status = Status.Error;
            res.Errors = GetModelStateErrorsAsString(this.ModelState);
            res.Message = "Oh dear, what have you done. Check the list of errors dude!";
        }
        else
        {
            // Save it here...
    
            // Return success
            res.Status = Status.Ok;
            res.Message = "Everything was hunky dory";
        }            
    
        return Json(res);
    }
    

    And the ModelStateDictionary can be enumerated for the errors as so:

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

    Then in my view I can have the following JSON POST:

    
    

    I'm using jQuery.tmpl to display the errors. I have excluded that from this example though.

提交回复
热议问题