5

我有AdvertiserNameAvailable远程验证属性正在使用的这种方法。问题是在AdvertiserNameAvailable没有将输入值传递给方法Name参数的情况下调用了。当我进入调试方法时,我看到Name参数总是null.

  public JsonResult AdvertiserNameAvailable(string Name)
  {
      return Json("Some custom error message", JsonRequestBehavior.AllowGet);
  }

  public class AdvertiserAccount
  {
      [Required]
      [Remote("AdvertiserNameAvailable", "Accounts")]
      public string Name
      {
          get;
          set;
      }
  }
4

2 回答 2

15

不得不添加[Bind(Prefix = "account.Name")]

public ActionResult AdvertiserNameAvailable([Bind(Prefix = "account.Name")] String name)
{
    if(name == "Q")
    {
        return  Json(false, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return  Json(true, JsonRequestBehavior.AllowGet);
    }
}

要找出您的前缀,请右键单击并检查您要验证的输入上的元素。寻找name属性:

<input ... id="account_Name" name="account.Name" type="text" value="">
于 2012-11-11T12:20:21.327 回答
0
[HttpPost]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult AdvertiserNameAvailable(string Name)
  {
    bool isNameAvailable = CheckName(Name);  //validate Name and return true of false
    return Json(isNameAvailable );     
  }

  public class AdvertiserAccount
  {
      [Required]
      [Remote("AdvertiserNameAvailable", "Accounts", HttpMethod="Post", ErrorMessage = "Some custom error message.")]     
      public string Name
      {
          get;
          set;
      }
  }

还要注意:

OutputCacheAttribute 属性是必需的,以防止 ASP.NET MVC 缓存验证方法的结果。

所以[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]在你的控制器动作上使用。

于 2012-11-11T12:25:04.573 回答