通过javascript提交表单后,将ModelState.AddModelError添加到视图中

时间:2018-07-06 12:57:33

标签: javascript c# asp.net-mvc razor

我是Web开发的新手。目前,我正在asp.net mvc 5上的一个实践项目上。我有一个供用户使用的表单,管理员可以在其中向系统添加新用户。新的用户表单将以模式形式打开,并以表单格式提交

查看

@using (Html.BeginForm("AddUser", "User", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))

{

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

@Html.AntiForgeryToken()
<div class="form-horizontal">
    <div class="modal-header">
        <h4 class="modal-title" id="myModalLabel">Add New User</h4>
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.user_name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-8">
            @Html.EditorFor(model => model.user_name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.user_name, "", new { @class = "text-danger" })
            @Html.ValidationMessage("UserExist", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.role_id, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.role_id, new SelectList(ViewBag.roles, "role_id", "role_name"), "Select", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.role_id)
        </div>
    </div>  


    <div class="form-group">
        @Html.LabelFor(model => model.user_password, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.user_password, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.user_password, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.confirmPassword, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.confirmPassword, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.confirmPassword, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.user_email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.user_email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.user_email, "", new { @class = "text-danger" })
            @Html.ValidationMessage("EmailExist", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.supervisor, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.supervisor, new SelectList(ViewBag.supervisors, "user_id", "user_name"), "Select Supervisor", new { @class = "form-control" })
        </div>

    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.region_id, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(model => model.region_id, new SelectList(ViewBag.regions, "region_id", "region_name"), "Select Region", new { @class = "form-control" })
        </div>
        @Html.ValidationMessageFor(model => model.region_id, "", new { @class = "text-danger" })
    </div>

    <div class="form-group">
        <input type="submit" id="submitBtn" value="Submit" class="btn btn-primary" />
        <input type="reset" value="Reset" class="btn" />
    </div>

</div>

}

JavaScript提交功能

function SubmitForm(form) {
        if ($(form).valid()) {
            $.validator.unobtrusive.parse(form);
            $.ajax({
                type: "POST",
                url: form.action,
                data: $(form).serialize(),
                success: function (data) {
                    if (data.success) {
                        $('#myModal').modal('hide');
                        //Popup.dialog('close');
                        dataTable.ajax.reload();

                        //notify.js plugin
                        $.notify(data.message, {
                            globalPosition: "top center",
                            className: "success"
                        })
                    }
                }                    
            });
        }
        return false;
    }

提交后,表单转到POST操作结果,该结果可以正常工作,并且创建了新用户,但是当我尝试添加模型错误时

#region User Already Exists
            var isUserExists = isUserExist(newUser.user_name);
            if (isUserExists)
            {
                ModelState.AddModelError("UserExist", "User already exists");
                return View(newUser);
            }
            #endregion

模型错误未反映在视图中。调试后,我发现POST操作结果中的模型未返回,并且使用了先前的模型。我已经处理此问题很长时间了,找到了一些可能的解决方案,但似乎没有一个可行。任何帮助或指导感将不胜感激。

在这里使用遥控器是ViewModel

public class AddUser
{
    [Display(Name = "User name")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "User name is required")]
    public string user_name { get; set; }

    [Display(Name = "Role")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password is required")]
    public int role_id { get; set; }

    [Display(Name = "Password")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Password is required")]
    [DataType(DataType.Password)]
    [MinLength(6, ErrorMessage = "Minimum 6 characters required")]
    public string user_password { get; set; }


    [Display(Name = "Confirm Password")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm Password is required")]
    [DataType(DataType.Password)]
    [System.ComponentModel.DataAnnotations.Compare("user_password", ErrorMessage = "Confirm password and password do not match")]
    public string confirmPassword { get; set; }

    [Display(Name = "Email")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Email is required")]
    [DataType(DataType.EmailAddress)]
    [System.Web.Mvc.Remote("CheckExistingEmail", "ModelValidation", HttpMethod = "POST", ErrorMessage = "Email already exists")]
    public string user_email { get; set; }

    [Display(Name = "Supervisor")]
    public Nullable<int> supervisor { get; set; }

    [Display(Name = "Region")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "User Region is required")]
    public int region_id { get; set; }


}

这是ValidationController

public class ModelValidationController : Controller
{
    [AllowAnonymous]
    [HttpPost]
    public ActionResult CheckExistingEmail(string Email)
    {
        try
        {
            return Json(!IsEmailExist(Email));
        }
        catch (Exception ex)
        {
            return Json(false);
        }
    }

    [NonAction]
    public bool IsEmailExist(string email)
    {
        using (mmpEntities mP = new mmpEntities())
        {
            var v = mP.users.Where(a => a.user_email == email).FirstOrDefault();
            //return v == null ? false : true;
            return v != null;
        }
    }

}

2 个答案:

答案 0 :(得分:1)

为进行验证,您可以使用jquery模块不引人注目的js,当您键入误导性输入时,它将为您提供实时jquery错误功能。这是使用方法:

<script src=" jquery.validate.min.js"></script>
<script src="jquery.validate.unobtrusive.min.js"></script>
<script src="~/vendors/jquery.form.min.js"></script>
<script>
  $(document).ready(function () {
            $(document).on("click", "#Subscribe", function () {
                $('#SubscribeForm').ajaxForm({
                    success: function (response) {
                        if (response.Success) {
// You could use toastr notifaction in here } 
else {
                          // You could use toastr notifaction in here
                        }
                    }
                })
            })
        })
</script>

答案 1 :(得分:0)

这是我在控制器内执行的操作,以通过ajax中的成功(或完成)将模型状态发送回客户端:

if (ModelState.IsValid)
{
   //your post code to db

}
else
{
   var modelState = ModelState.ToDictionary
   (
       kvp => kvp.Key,
       kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()

   );
  return Json(new { modelState = modelState }, JsonRequestBehavior.AllowGet);
}

然后在ajax成功或完成的回调中执行以下操作:

 if (data.modelState) {
     $.each(data.modelState, function (i, item) {
       item.valid(); //run jQuery validation to display error
     }
  }