且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.Net MVC 3 JSON模型绑定和客户端验证服务器端模型验证混合

更新时间:2023-02-25 14:04:22

下面的例子中使用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.