MVC 5验证消息不适用于使用Ajax.beginForm

时间:2014-05-04 08:54:31

标签: c# jquery ajax asp.net-mvc

我是MVC 5的新手,我遇到了一些问题,我无法找到任何答案,但我没有尝试,但没有成功。

我尝试对用户和密码列表进行验证,以确保他们输入数据并且不要将其留空,然后检查用户是否存在于数据库中,但由于某种原因,它根本不起作用。

Controller:UserController.cs

    [HttpGet]
    [Authorize(Roles = "Admin")]
    public ActionResult EditUser()
    {

        return PartialView("_EditUser", employeeRepository.GetAllEmployees());
    }

    [HttpPost]
    [Authorize(Roles = "Admin")]
    public ActionResult UpdateEmployees(UserDetailViewModel[] EmployeeList)
    {



        if (ModelState.IsValid)
        {
            if (EmployeeList != null)
            {
                employeeRepository.UpdateEmployee(EmployeeList);

                return PartialView("_EditUser", EmployeeList);



            }

        }
        ModelState.AddModelError("UserName", "User allready exists");
        return PartialView("_EditUser", "UserDetailViewModel");
    }

模型:UserViewModel.cs它有2个类,但我使用的是UserDetailViewModel

public class UserDetailViewModel
{

    public int ID { get; set; }

    [Required (AllowEmptyStrings = false, ErrorMessage = "Username is required")]
    public string UserName { get; set; }

    public string WindowsID { get; set; }

    [DataType(DataType.Password)]
    [Required (AllowEmptyStrings = false, ErrorMessage = "Password is required")]
    public string Password { get; set; }

    public bool isAdmin { get; set; }
    public bool isExternal { get; set; }
    public bool isDeleted { get; set; }

    public bool isModified { get; set; }
}

查看:_EditUser.cshtml

我使用弹出式fancy_box.js脚本.Render包含jquery.validate.js",jquery.validate.unobtrusive.js",jquery.unobtrusive-ajax.js& #34;,

    @model OfficeManager.Interfaces.ViewModels.UserDetailViewModel[]

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
@using (Ajax.BeginForm("UpdateEmployees", "User", new AjaxOptions
{
        HttpMethod = "POST",
        InsertionMode = InsertionMode.Replace,
        OnSuccess = "usersSavedSuccessfully",
        OnFailure = "failedSaveUsers"
    }, new { id = "editUser" }))
{
    <div class="edit-pop-up gray2">
        <div class="edit-title orangeGray"><h3>Edit User</h3></div>
        <table id="Edit_user_table" align="center">
            @Html.ValidationSummary(false)
            <thead>
                <tr>
                    <td><p>UserName:</p></td>
                    <td><p>WindowsID:</p></td>
                    <td><p>Password:</p></td>
                    <td><p>Admin:</p></td>
                    <td><p>External:</p></td>
                    <td><p>Deleted:</p></td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td colspan="6">
                        <div id="edit_user_inner">
                            <table id="inner_edit_user_table">
                @foreach (var item in Model)
                {
                    <tr id="item-@(item.ID)">
                        <td>@Html.EditorFor(model => item.UserName, new { @class = "editUser" })
                        @Html.ValidationMessage("UserName")</td>

                        <td>@Html.EditorFor(model => item.WindowsID, new { @class = "" })</td>

                        <td>@Html.EditorFor(model => item.Password, new { @class = "" })
                        @Html.ValidationMessageFor(model => item.UserName)</td>

                        <td>@Html.EditorFor(model => item.isAdmin)</td>
                        <td>@Html.EditorFor(model => item.isExternal)</td>
                                        <td>
                                            @Html.EditorFor(model => item.isDeleted)
                                            @Html.HiddenFor(model => item.isModified)
                                        </td>
                    </tr>
                }
                            </table>
                        </div>
                    </td>
                </tr>

            </tbody>
        </table>
        <div style="margin-left: 5px; padding-right:14px; padding-bottom: 16px; border: 0px none; float: right;;">
            <input id="add_user" onclick="AddRow()" type="button"  value="Add New User" class="btn btn-default" style="margin-left: auto; margin-top: 20px; font-size: 20px; width:auto;" />
            <input id="save_user" type="submit" class="btn btn-default" style="margin-left: auto; margin-top: 20px; font-size: 20px; width: auto;" />
            <input id="cancel_user" type="button" onclick="$.fancybox.close();" value="Cancel" class="btn btn-default " style="margin-left: auto; margin-top: 20px; font-size: 20px; width: auto;" />
        </div>
    </div>
}

当我按下提交按钮时,我收到此错误:

POST http://localhost:54238/User/UpdateEmployees?Length=4 500 (Internal Server Error) 

但是该消息不会显示,但会在onFailure上显示Ajax.BeginForm

那可能是什么原因?我尝试了不同的方式,我设法使其工作的唯一方法是使用jQuery而不是返回View我使用返回JSON和自定义消息,我通过读取控制器的响应,使用jQuery更改它,但这并不是它应该完成的方式。

1 个答案:

答案 0 :(得分:0)

在简单的项目中 控制器:

 public class AccountController : Controller
    {
        public AccountController()
        {
            HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
        }
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(Account model)
    {
        if (ModelState.IsValid)
        {
            return PartialView("Thanks");
        }
        return PartialView("Index");
    }
}

viewModel:

public class Account
{
    [Required]
    [StringLength(20, MinimumLength = 4)]
    public string Username { get; set; }

    [Required]
    [StringLength(20, MinimumLength = 4)]
    [Compare("ConfirmPassword")]
    public string Password { get; set; }

    [Required]
    [StringLength(20, MinimumLength = 4)]
    [Compare("Password")]
    [DisplayName("Confirm Password")]
    public string ConfirmPassword { get; set; }

    [Required]
    [AgeValidation(21)]
    [DisplayName("Birth Date")]
    public DateTime BirthDate { get; set; }
}

视图:                               

<body>
    <div id="ParentDiv">
        <div id="Aj">
@{ var ajaxOptions = new AjaxOptions
       {
           UpdateTargetId = "ParentDiv",
           HttpMethod = "POST"
       }; }
@using (Ajax.BeginForm("Index", "Account", ajaxOptions))
{
    @Html.EditorForModel()
    <input type="submit" />
}
</div>
    </div>
</body>

你可以看到&gt; http://www.codeproject.com/Articles/460893/Unobtrusive-AJAX-Form-Validation-in-ASP-NET-MVC