2016-03-16 33 views
3

我想如下创建远程验证:使用远程验证与ASP.NET核心

[Remote("CheckValue", "Validate", ErrorMessage="Value is not valid")] 
public string Value { get; set; } 

我使用ASP.NET核心(ASP.NET 5),它似乎很遥远不可用。 有谁知道如何用ASP.NET CORE做到这一点?

回答

5

的RemoteAttribute是ASP.Net MVC核心的部分:

  • 如果使用RC1,它是在Microsoft.AspNet.Mvc命名空间。请参阅github中的RemoteAttribute
  • 在RC2中计划重命名后,它将位于Microsoft.AspNetCore.Mvc命名空间中。请参阅github中的RemoteAttribute

例如,在RC1中创建一个具有身份验证的新MVC站点。然后更新生成LoginViewModel与虚拟远程验证调用在家里控制器的方法:

using Microsoft.AspNet.Mvc; 
using System.ComponentModel.DataAnnotations; 
public class LoginViewModel 
{ 
    [Required] 
    [EmailAddress] 
    [Remote("Foo", "Home", ErrorMessage = "Remote validation is working")] 
    public string Email { get; set; } 

    ... 
} 

如果您创建家庭中的控制器虚拟方法和设置断点,你会看到它被击中时,你改变电子邮件登录表单:

public class HomeController : Controller 
{ 

    ... 

    public bool Foo() 
    { 
     return false; 
    } 
} 
+0

你是对的...我在看System.Component.DataAnnotations,我甚至在Github上找到了这个库源代码。当然它在Microsoft.AspNet.Mvc。谢谢! –

0

在此期间,该文件是存在的,可用here。简单来说,您只需要使用下面的装饰您的视图模型的财产:

[Remote(action: "Foo", controller: "Bar", ErrorMessage = "Remote validation is working")] 
    [Required]   
    [Display(Name = "Name")] 
    public string Name { get; set; } 

然后创建控制器(在这个例子中名为“酒吧”)的动作(在这个例子中名为“富”),并添加你的逻辑有:

[AcceptVerbs("Get", "Post")] 
    public async Task<IActionResult> Foo(string name) 
    { 
     bool exists = await this.Service.Exists(name); 
     if (exists) 
      return Json(data: false); 
     else 
      return Json(data: true); 
    } 

最后说明:远程属性为Microsoft.AspNetCore.Mvc命名空间。