2016-08-07 33 views
1

我試圖實現簡單的CMS。我有Page類的實例,我想將其添加到數據庫並編輯它們。 Page中的UrlName應該是唯一的,所以我創建了自定義驗證器,但是,在編輯時,如果不將UrlName更改爲未出現的格式,我無法提交表單。我如何將額外的數據傳遞給我的VerifyUrl或者有另一種方法可以解決這個問題?ASP.NET MVC應用程序中的不同驗證操作

public class Page : IUpdatable<Page> 
{ 
    public int ID { get; set; } 
    [Required] 
    [DataType(DataType.Url)] 
    [Remote(action: "VerifyUrl", controller: "Pages")] 
    public string UrlName { get; set; } 
} 

這是PagesController

public JsonResult VerifyUrl(string UrlName) 
{ 
    if (!db.Pages.Any(x => x.UrlName.Equals(UrlName))) 
     return Json(data: true); 
    return Json(data: "This Url is already in use"); 
} 

我的驗證方法,而這在我看來是

<input asp-for="UrlName" class="form-control" /> 
<span asp-validation-for="UrlName" class="text-danger" /> 
+0

請不要將[標籤:asp.net-mvc]用於ASP.NET Core,請使用[標籤:asp.net-core-mvc] – Tseng

回答

0

註明「此網址已經在使用」在遠程的ErrorMessage和你的行動Mehtod,在Json中返回false如果提供的URL已經是Use。

Model類

[DisplayName("URL")] 
    [Required] 
    [Remote("Validate", "Home", HttpMethod = "Post", ErrorMessage = "This URL already exists")] 
    public string URL { get; set; } 

在你的控制器

[HttpPost] 
    public ActionResult Validate(string URL) 
    { 
     //Do validation here from DataBas 
     //if URL already exist, return false, else true; 

      return Json(false); 

    } 

Working Demo

要傳遞更多的信息到你的控制器的方法,你可以在遠程屬性指定其他字段:

 [DisplayName("User name")] 
    [Required] 
     public string UserName { get; set; } 

     [DisplayName("URL")] 
     [Required] 
     [Remote("Validate", "Home", HttpMethod = "Post",AdditionalFields="UserName", ErrorMessage = "This URL and Username should not be same")] 
    public string URL { get; set; } 


[HttpPost] 
    public ActionResult Validate(string URL, string UserName) 
    { 
     if(URL == UserName) 
      return Json(false); 
     else 
      return Json(true); 

    } 

Woking Demo for additional field

+0

你剛剛做了,我做了什麼。我在我的問題中提供了所有這些代碼。它可以完美地將實例添加到數據庫中。當我編輯現有的實例時,我的問題是驗證Url –

+0

在第一個示例中,我只是向您展示瞭如何在遠程屬性中使用錯誤消息。第二個示例展示'我如何將額外數據傳遞給'VerifyUrl'' – mmushtaq

+0

謝謝,當我評論時,沒有關於如何傳遞額外數據的信息。這真的幫助了我。 –

0

您是否允許用戶在編輯帖子時更改網址?如果沒有,我會創建單獨的視圖模型,一個用於「新郵政」,另一個用於「編輯郵政」。

新帖子視圖模型可以調用驗證方法。在編輯時,只要您不允許用戶更改UI中的URL,您就不需要重新驗證它。

相關問題