ASP.Net MVC 3 JSON模型绑定和客户端验证服务器端模型验证混合 [英] ASP.Net MVC 3 JSON Model Binding and server side model validation mixed with client side validation

查看:125
本文介绍了ASP.Net MVC 3 JSON模型绑定和客户端验证服务器端模型验证混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩新的MVC3的Json模型绑定,这是相当不错的。

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

目前,我可以张贴JSON来控制器和绑定。太漂亮模型验证时发生。

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

但是,如果该模型是无效的,会发生什么?

我想返回JSON并让客户端通知用户(如你会如何执行正常的MVC客户端验证)

I'd like to return JSON and have the client side notify the user (like how you'd perform normal client side validation in mvc)

有谁知道如何执行此部分教程?

Does anyone know of some tutorials on how to perform this?

这甚至可能吗?

还是有框架,我可以利用这样做?

Or are there frameworks I can leverage to do this?

推荐答案

下面的例子中使用MVC3非侵入式JavaScript时,我的作品。我在做一些非常相似。鉴于以下 JsonResponse 类:

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<string> 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);
}

而ModelStateDictionary可以列举的错误,像这样:

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

private List<string> GetModelStateErrorsAsString(ModelStateDictionary state)
{
    List<string> errors = new List<string>();

    foreach (var key in ModelState.Keys)
    {
        var error = ModelState[key].Errors.FirstOrDefault();
        if (error != null)
        {
            errors.Add(error.ErrorMessage);
        }
    }

    return errors;
}

然后在我看来,我可以有以下的JSON POST:

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

<script type="text/javascript">
$("form").submit(function (evt) {
    // validate
    $('form').valid();

    // extract values to submit         
    var form = $(this),
        username = form.find("[name=Username]").val(),
        password = form.find("[name=Password]").val(),
        json = JSON.stringify({
            Username: username,
            Password: password
        });

    $.ajax({
        url: form.attr("action"),
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: json,
        success: function (result) {
            alert(result.Message);
        }
    });

    // stop form submitting
    evt.preventDefault();
});
</script>

我用 jQuery.tmpl 显示错误。我已经排除,从这个例子虽然。

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

这篇关于ASP.Net MVC 3 JSON模型绑定和客户端验证服务器端模型验证混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆