MVC 3通过ajax访问模型错误

时间:2013-07-01 13:51:12

标签: .net ajax json asp.net-mvc-3

我正在开发一个相当大的MVC 3 Web应用程序。在过去的几年中,各种不同技能的程序员都在研究这一问题,因此理解这一切是一个缓慢而令人沮丧的过程。

目前我的主要问题是试图通过以下代码了解以前的工作人员究竟在尝试什么:

以下是视图CreatePartial(尽管未用作局部视图)

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<RetainedAvailability.ViewModels.CreateAccountViewModel>" %>
<script type="text/javascript">
    SetupCreateView();
    $(document).ready(function () { $('input:submit,button').button(); });
</script>
    <h2>Create a New Account</h2>
    <p>
        Use the form below to create a new account. 
    </p>
    <p>
        Passwords are required to be a minimum of <%:ViewData["PasswordLength"]%> characters in length.
    </p>

<form id="CreateForm" runat="server">
        <%:Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")%>
        <div>
            <fieldset>
                <legend>Account Information</legend>

                <div class="editor-label">
                    <%:Html.LabelFor(m => m.User.UserName)%>
                </div>
                <div class="editor-field">
                    <%:Html.TextBoxFor(m => m.User.UserName)%>
                    <%:Html.ValidationMessageFor(m => m.User.UserName)%>
                </div>

                <%:Html.ValidationMessageFor(m => m.User.Email)%>
                <%:Html.HiddenFor(m => m.User.Email)%>

                <div class="editor-label">
                    <%:Html.LabelFor(m => m.User.Password)%>
                </div>
                <div class="editor-field">
                    <%:Html.PasswordFor(m => m.User.Password)%>
                    <%:Html.ValidationMessageFor(m => m.User.Password)%>
                </div>

                <div class="editor-label">
                    <%:Html.LabelFor(m => m.User.ConfirmPassword)%>
                </div>
                <div class="editor-field">
                    <%:Html.PasswordFor(m => m.User.ConfirmPassword)%>
                    <%:Html.ValidationMessageFor(m => m.User.ConfirmPassword)%>
                </div>

                <div class="editor-label">
                    <%:Html.LabelFor(m => m.User.Role)%>
                </div>
                <div class="editor-field">
                    <%:Html.DropDownListFor(m => m.User.Role, Model.Roles)%>
                    <%:Html.ValidationMessageFor(m => m.User.Role)%>
                </div>
                <p>
                    <input type="submit" value="Register" />
                </p>
            </fieldset>
        </div>
</form>

这是相关的控制器方法

[HttpPost]
[Authorize(Roles = "Administrator,StationManager")]
public ActionResult CreatePartial(RegisterModel User)
{
    if (ModelState.IsValid)
    {
        // Attempt to register the user and get status
        MembershipCreateStatus createStatus = MembershipService.CreateUser(User.UserName, User.Password, User.Email);

        // If successful registration, update the db
        if (createStatus == MembershipCreateStatus.Success)
        {
            // Link role and user
            Roles.AddUserToRole(User.UserName, User.Role);
            // Link station and user
            _repository.LinkUserToStation(User.UserName, (Guid) Session["StationID"]);
            // Save tables
            _repository.SaveChanges();

            // Create success notification
            var res = new AjaxResponse<CrewMember>
            {
                Data = null,
                IsSuccess = true,
                GrowlNotification = "Created " + User.UserName
            };
            // Return notification
            return new JsonResult {Data = res, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
        }
        else
        {
            ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
        }
    }

    // If we got this far, something failed, redisplay form
    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;

    var Errors = ModelState.Where(e => e.Value.Errors.Any()).Select(ee => ee.Value.Errors.First().ErrorMessage).ToList();

    var res1 = new AjaxResponse<dynamic>
    {
        Data = null,
        IsSuccess = false,
        Errors =
            ModelState.Where(e => e.Value.Errors.Any()).Select(
                ee => ee.Value.Errors.First().ErrorMessage).ToList()
    };

    return new JsonResult {Data = res1, JsonRequestBehavior = JsonRequestBehavior.AllowGet};
}

因此,您可以看到任何模型错误都封装在AjaxResponse中,然后作为JsonResult传递,我希望将其传递回视图。

问题是,一旦视图中的表单与无效数据一起使用(这是我正在测试的)没有任何反应。没有错误消息。我假设视图端会缺少一些将使用JsonResult的javascript。视图中的验证类似乎没有被使用。

还没有返回视图,只有JsonResult,这对于ASP.NET MVC是否可接受?

修改

以下JS处理表单的验证。尽管视图已经使用了验证实体,但它会手动将错误应用于DOM。它只是我还是一种不必要的冗长的验证形式的方式?

    function ShowValidationErrors(data) {
        $('#CreateForm input[type=text]').removeClass("ui-state-error");
        $('#CreateForm label').css('font-weight', 'normal');
        $('.field-validation-error').remove();
        for (var i = 0; i < data.Errors.length; i++) {
            $('#CreateForm label[for=' + recordName + '_' + data.Errors[i].Target + '], #CreateForm label[for=' + data.Errors[i].Target + ']').css('font-weight', 'bold');
            //     $('#CreateForm #' + recordName + '_' + data.Errors[i].Target +', #CreateForm #' + data.Errors[i].Target).attr('class', 'input-validation-error');
            $('#CreateForm #' + recordName + '_' + data.Errors[i].Target + ', #CreateForm #' + data.Errors[i].Target).addClass("ui-state-error");
            $('<p class="field-validation-error">* ' + data.Errors[i].Message + '</p>').insertAfter('#CreateForm #' + recordName + '_' + data.Errors[i].Target);
            $('<p class="field-validation-error">* ' + data.Errors[i].Message + '</p>').insertAfter('#CreateForm #' + data.Errors[i].Target);
            $('.input-validation-error:first').focus();
        }
    }

0 个答案:

没有答案