繁体   English   中英

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

[英]MVC 5 Validation Message doesn't work with using Ajax.beginForm

我是MVC 5的新手,但遇到了一些问题,找不到以其他方式尝试过的任何答案,但均未成功。

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

控制器: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作为弹出窗口。渲染包含jquery.validate.js“,jquery.validate.unobtrusive.js”,jquery.unobtrusive-ajax.js“,

    @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) 

但该消息没有出现,但它会onFailureAjax.BeginForm

那是什么原因呢? 我以不同的方式尝试过,我设法使其正常工作的唯一方法是使用jQuery,而不是return View ,而是使用带有自定义消息的return JSON,并通过读取控制器的响应来使用jQuery对其进行了更改,但这不是应该完成的方式。

在简单的项目控制器中:

 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>

您可以看到> http://www.codeproject.com/Articles/460893/Unobtrusive-AJAX-Form-Validation-in-ASP-NET-MVC

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM