c# - 远程属性验证未在 Asp.Net MVC 中触发

标签 c# jquery asp.net-mvc-3 remote-validation

这是我的模型代码

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

在我的 Controller 中我有

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>}

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

最佳答案

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

[AllowAnonymous]
public JsonResult IsNameAvailable(string Name)

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

关于c# - 远程属性验证未在 Asp.Net MVC 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19680967/

相关文章:

c# - F# 动态对象访问

c# - 具有参数的WPF Mvvm导航

c# - 通过 GSM 调制解调器接收短信

visual-studio-2010 - 条件编译不起作用

c# - 一个 C# 数据结构,用于保存具有不同于 "key"和 "value"的标识符的键值对

jquery - 如何使用jquery获取表元素中的 "td"?

javascript - 如果 e.keyCode 是 "enter"按钮并且元素包含其他文本,则条件已验证

javascript - 如何在 MVC3 中将鼠标悬停在文本上时显示部分 View ?

c# - 将依赖项注入(inject) ASP.NET MVC 3 操作过滤器。这种方法有什么问题?

c# - 在MVC3的下拉列表中设置所选项目