none
Remote验证的问题(MVC) RRS feed

  • 问题

  • Model

    [Remote("CheckProductName","Product",ErrorMessage ="该产品名称已经存在")]
    public virtual string Title { get; set; }

    Controller

    public JsonResult CheckProductName(string Title)
            {
                var result = db.Products.Where(p => p.Title.Contains(Title)).Count()==0;
                return Json(result, JsonRequestBehavior.AllowGet);
            }

    在调试的时候发现CheckProductName里面的代码根本没有被执行过,不知道问题出在哪里了

    2017年8月6日 7:38

全部回复

  • Model

       public class Product
        {
            [Key]
            [Display(Name ="编号")]
            public virtual int ProdeuctId { get; set; }
    
            [Display(Name ="所属分类")]        
            public virtual int CategoryId { get; set; }
            
                    
            [Required(ErrorMessageResourceName ="E0002",ErrorMessageResourceType =typeof(Messages))]
            [StringLength(maximumLength:20,MinimumLength =2,ErrorMessageResourceName = "E0001", ErrorMessageResourceType =typeof(Messages))]
            [Display(Name ="ProductName",ResourceType =typeof(Resources.Test))]
            [Remote("CheckProductName","Product",ErrorMessage ="该产品名称已经存在")]
            public virtual string Title { get; set; }
    
            [Display(Name ="ProductPrice",ResourceType =typeof(Resources.Test))]
            [Range(1,99,ErrorMessageResourceType =typeof(Messages),ErrorMessageResourceName ="E0003")]
            public virtual double Price { get; set; }
    
            [Display(Name ="描述")]
            public virtual string Content { get; set; }
            public virtual Category Category { get; set; }
        }

    Controller

            public JsonResult CheckProductName(string Title)
            {
                var result = db.Products.Where(p => p.Title.Contains(Title)).Count()==0;
                return Json(result, JsonRequestBehavior.AllowGet);
            }

            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create([Bind(Include = "ProdeuctId,CategoryId,Title,Price,Content")] Product product)
            {
                if (ModelState.IsValid)
                {
                    db.Products.Add(product);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
    
                ViewBag.CategoryId = new SelectList(db.Categorys, "CategoryId", "Name", product.CategoryId);
                return View(product);
            }

    在Create的时候,并没有触发这个验证

    2017年8月6日 10:23
  • 你好,

    -->没有触发验证

    我觉得原因可能是相关的JQuery引用没有添加成功,你可以使用F12去检测一下。

    另外你也可以参考下边的示例:

    Controller中的代码:

            [HttpGet]
            public ActionResult TestRemote()
            {
                return View();
            }
            [HttpPost]
            public ActionResult TestRemote(Test info)
            {
                return View();
            }
            [HttpGet]
            public JsonResult CheckPhone(string Phone)
            {
                List<Test> itemlist = new List<Test>()
                {
                    new Test() { Id=1001, Phone="123" },
                    new Test() { Id=1002, Phone="234" },
                    new Test() { Id=1003, Phone="345" }
                };
    
                bool isExist = itemlist.Where(u => u.Phone.Equals(Phone)).FirstOrDefault() == null;
                return Json(isExist, JsonRequestBehavior.AllowGet);
            }

    Model:

        public class Test
        {
            [Key]
            public int Id { get; set; }
            [System.Web.Mvc.Remote("CheckPhone", "Home", ErrorMessage = "Existed!")]
            public string Phone { get; set; }
        }

    View:你可以使用Script.Render去添加JQuery引用,或者直接添加引用:

    @section scripts
    {
        @Scripts.Render("~/bundles/jqueryval")
    }
      
    @*<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>*@
    @using (Html.BeginForm()) 
    {
        @Html.AntiForgeryToken()
        
        <div class="form-horizontal">
            <h4>Test</h4>
            <hr />
            @Html.ValidationSummary(true)
            <div class="form-group">
                @Html.LabelFor(model => model.Phone, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Phone)
                    @Html.ValidationMessageFor(model => model.Phone)
                </div>
            </div>
    
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </div>
        </div>
    }

    BundleConfig.cs:

        public class BundleConfig
        {
            // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js",
                          "~/Scripts/respond.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css"));
            }
        }

    Web.config:

      <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
      </appSettings>

    运行结果如下:


    2017年8月8日 7:57
    版主