ASP.NET MVC Remote attribute method parameter alwa

2019-04-08 23:55发布

问题:

I have this AdvertiserNameAvailable method that is being used by Remote validation attribute. The problem is that the AdvertiserNameAvailable is being called without passing the input value to the method Name parameter. When I enter in debug into the method, I see that the Name parameter is always 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;
      }
  }

回答1:

Had to add [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);
    }
}

To find out your prefix, right click and do inspect element on the input that you are trying to validate. Look for the name attribute:

<input ... id="account_Name" name="account.Name" type="text" value="">


回答2:

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

Also to note:

The OutputCacheAttribute attribute is required in order to prevent ASP.NET MVC from caching the results of the validation methods.

So use [OutputCache(Location = OutputCacheLocation.None, NoStore = true)] on your controller action.