7

这是我的模型代码

public class BlobAppModel
{
   [Required(ErrorMessage="Please enter the name of the image")]
   [Remote("IsNameAvailable","Home",ErrorMessage="Name Already Exists")]
   public string Name { set; get; }           
}

在我的控制器中,我有

public JsonResult IsNameAvailable(string Name)
{
   bool xx= BlobManager.IsNameAvailable(Name);
   if (!xx)
   {
      return Json("The name already exists", JsonRequestBehavior.AllowGet);
   }
   return Json(true, JsonRequestBehavior.AllowGet);
}

在我的数据中,我有

public static bool IsNameAvailable(string Name)
{
   var test = "";
   using (var x = new BlobTestAppDBEntities())
   {
       try
       {
            test=x.BlobApps.Where(m => m.Name == Name).FirstOrDefault().Uri;
            if (test != null)
               return false;
            else
               return true;
       }
       catch (Exception)
       {
          return true;
       }
   }
}

在我看来,我也添加了脚本

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {

    <td> @Html.Label("Name:") 
                 @Html.TextBoxFor(m => m.Name)
                 @Html.ValidationMessageFor(m=>m.Name)</td>}

但是远程验证根本没有触发..我的代码有问题吗?

4

4 回答 4

13

确保您的验证方法带有 [AllowAnonymous] 属性(也可能需要 [HttpPost])。

[AllowAnonymous]
public JsonResult IsNameAvailable(string Name)

还有一个提示:使用浏览器的开发者工具(主要浏览器中的 F12 按钮)查看 Json 请求的状态。

于 2014-07-25T09:31:03.373 回答
5

您在视图中缺少该jquery.unobtrusive-ajax.js文件,请添加该文件并重试。

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

如果您没有它,请从 nuget 获取

nuget 链接http://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/

于 2013-10-30T12:15:25.770 回答
3

我知道这有点晚了,如果您使用的是 Razor 语法,我发现除了您所做的一切之外,您还需要:

@Scripts.Render("~/bundles/jqueryval")
于 2016-05-05T06:02:06.390 回答
2

这些设置也需要进入 web.config:

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
于 2013-11-26T21:00:40.457 回答