ASP.NET MVC Remote属性方法参数始终传递null

时间:2012-11-11 11:43:51

标签: asp.net-mvc asp.net-mvc-3

我有远程验证属性使用的这个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;
      }
  }

2 个答案:

答案 0 :(得分:13)

必须添加[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="">

答案 1 :(得分: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)]