2011-03-13 159 views
15

我有我試圖從使用該模型的屬性以下屬性的區域內使用我的項目的路線內的驗證控制器...ASP.NET MVC 3遠程驗證

[Remote("IsValidUserName", "Validation", "", ErrorMessage = "Invalid username")] 

但是,當這是渲染時,驗證是針對控制器「驗證」在與頁面相同的區域內的「IsValidUserName」動作,並且不在根區域內...

data-val-remote-url =「 /會員/驗證/ IsValidUserName「

任何幫助,將不勝感激。

謝謝。

回答

31

不幸的是,這是如何實現這個屬性。下面是該屬性的構造函數摘錄:

public RemoteAttribute(string action, string controller, string areaName) : this() 
{ 
    if (string.IsNullOrWhiteSpace(action)) 
    { 
     throw new ArgumentException(MvcResources.Common_NullOrEmpty, "action"); 
    } 
    if (string.IsNullOrWhiteSpace(controller)) 
    { 
     throw new ArgumentException(MvcResources.Common_NullOrEmpty, "controller"); 
    } 
    this.RouteData["controller"] = controller; 
    this.RouteData["action"] = action; 
    if (!string.IsNullOrWhiteSpace(areaName)) 
    { 
     this.RouteData["area"] = areaName; 
    } 
} 

通知對areaName在那的殺一切都結束了IsNullOrWhiteSpace測試?

你可以通過編寫自定義的遠程屬性修正:

public class MyRemoteAttribute : RemoteAttribute 
{ 
    public MyRemoteAttribute(string action, string controller, string area) 
     : base(action, controller, area) 
    { 
     this.RouteData["area"] = area; 
    } 
} 

然後:

[MyRemote("IsValidUserName", "Validation", "", ErrorMessage = "Invalid username")] 
public string Username { get; set; } 

現在正確data-val-remote-url="/Validation/IsValidUserName"將會產生。

+0

謝謝您的解決方案。 – user644344 2011-03-13 18:36:55

+0

你能告訴我在哪裏可以得到MVC的源代碼嗎? – user644344 2011-03-13 18:37:36

+0

@ user644344,它可以在這裏找到:http://aspnet.codeplex.com/releases/view/58781。但是您也可以使用Reflector快速瀏覽程序集。 – 2011-03-13 19:42:54

8

我遇到了同樣的問題,並找到了適用於我的解決方案。遠程屬性採用AreaReference枚舉。

System.Web.Mvc.AreaReference是具有兩個值UseRoot & UseCurrent更多的細節發現here

例使用率,對我的作品的ENUM:

[Remote("IsValidUserName", "Validation", System.Web.Mvc.AreaReference.UseRoot, ErrorMessage = "Invalid username")] 
+1

接受的答案是解決方法。這似乎是正確的答案。 – Sam 2015-09-22 15:12:13

+0

'AreaReference'直到MVC 5纔出現,因此接受的答案仍然有效。 – Mrchief 2016-06-14 03:36:53