首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >通过javascript提交表单后,将ModelState.AddModelError添加到视图中

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

Stack Overflow用户
提问于 2018-07-06 20:57:33
回答 2查看 2K关注 0票数 0

我是web开发的新手。目前我正在做一个关于asp.net MVC5的实践项目。我有一个用户表单,管理员可以在其中添加一个新用户到系统中。新用户表单将以模式打开,并以表单格式提交

视图

代码语言:javascript
复制
@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提交函数

代码语言: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操作结果,它工作正常,并创建了新用户,但当我尝试添加模型错误时

代码语言:javascript
复制
#region User Already Exists
            var isUserExists = isUserExist(newUser.user_name);
            if (isUserExists)
            {
                ModelState.AddModelError("UserExist", "User already exists");
                return View(newUser);
            }
            #endregion

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

此处使用remote是ViewModel

代码语言:javascript
复制
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

代码语言:javascript
复制
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;
        }
    }

}
EN

回答 2

Stack Overflow用户

发布于 2018-07-08 04:06:12

对于验证,您可以使用jquery模块不显眼的js,当您输入误导性输入时,它将为您提供实时的jquery错误功能。下面是你使用它的方法:

代码语言:javascript
复制
<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
EN

Stack Overflow用户

发布于 2018-07-06 21:36:02

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

代码语言:javascript
复制
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 }, JsonRequestBehavior.AllowGet);
}

然后在ajax的success or done回调中执行如下操作:

代码语言:javascript
复制
 if (data.modelState) {
     $.each(data.modelState, function (i, item) {
       item.valid(); //run jQuery validation to display error
     });
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51210945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档