微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过ajax进行模型绑定和发布形式

如何解决通过ajax进行模型绑定和发布形式

| 我想通过ajax调用发布表单,模型也将被传递到action方法中,但是想通过json获得模型错误。我怎样才能做到这一点?     

解决方法

        您可以编写一个自定义操作过滤器:
public class HandleJsonErrors : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var modelState = (filterContext.Controller as Controller).ModelState;
        if (!modelState.IsValid)
        {
            // if the model is not valid prepare some JSON response
            // including the modelstate errors and cancel the execution
            // of the action.
            // TODO: This JSON could be further flattened/simplified
            var errors = modelState
                .Where(x => x.Value.Errors.Count > 0)
                .Select(x => new
                {
                    x.Key,x.Value.Errors
                });
            filterContext.Result = new JsonResult
            {
                Data = new { isvalid = false,errors = errors }
            };
        }
    }
}
然后付诸行动。 模型:
public class MyViewModel
{
    [StringLength(10,MinimumLength = 5)]
    public string Foo { get; set; }
}
控制器:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [HandleJsonErrors]
    public ActionResult Index(MyViewModel model)
    {
        // if you get this far the model was valid => process it
        // and return some result
        return Json(new { isvalid = true,success = \"ok\" });
    }
}
最后是请求:
$.ajax({
    url: \'@Url.Action(\"Index\")\',type: \'POST\',contentType: \'application/json; charset=utf-8\',data: JSON.stringify({
        foo: \'abc\'
    }),success: function (result) {
        if (!result.isvalid) {
            alert(result.errors[0].Errors[0].ErrorMessage);
        } else {
            alert(result.success);
        }
    }
});
    ,        像这样吗
  $.ajax({
                    type: \"POST\",url: $(\'#dialogform form\').attr(\"action\"),data: $(\'#dialogform form\').serialize(),success: function (data) {
                        if(data.Success){
                          log.info(\"Successfully saved\");
                          window.close();
                        }
                        else {
                          log.error(\"Save failed\");
                          alert(data.ErrorMessage);
                    },error: function(data){
                        alert(\"Error\");
                    }
                });


    [HttpPost]
    public JsonResult SaveServiceReport(Model model)
    {
        try
        {
            //
        }
        catch(Exception ex)
        {
            return Json(new AdminResponse { Success = false,ErrorMessage = \"Failed\" },JsonRequestBehavior.AllowGet);
        }
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。