2016-04-27 62 views
0

我已經創建了一個數據庫,添加了實體框架逆向工程(在一個Dll中)。我創建了編輯視圖,刪除方法,一切工作正常。如何爲由Entity Framework創建的模型進行驗證?

我需要添加驗證。怎麼做?

using System; 
using System.Collections.Generic; 

namespace MyDLL.Models 
{ 
    public partial class ContactNumberTable 
    { 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public string PhoneNumber { get; set; } 
    } 
} 

這個C#文件是在我的dll項目引用模型中自動創建的。

回答

0

編輯

首先開始的這就是所謂Data Annotations。要驗證添加到您的Model您可以添加Required[(ErrorMessage="")]這是您要驗證像任何價值DataAnnotation Class低於

[Required(ErrorMessage = "Validation message here")]//this is what sets the validation message 
public string Name { get; set; } 

然後在您的View中,您必須執行以下操作以在需要時顯示驗證消息:

@Html.TextBoxFor(x => x.Name) 
@Html.ValidationMessageFor(x => x.Name, new { @class = "text-danger" })//this is the part the gets the validation error message 

這樣做的目的是獲取將驗證消息放入您的View中的值的錯誤消息。你可以爲你想要的任何值進行驗證。

編輯

有幾個Data Annotation類,您可以使用,你可以在這裏閱讀更多Link這裏Entity Framework DataAnnotations

0

只是延長jamiedanq答案,如果你只需要進行現場爲「 REQUIRED「然後把

[Required(ErrorMessage="your message")] 

在您的屬性的頂部。

你的領域的頂級

如果您需要驗證數據庫從一些外地(你需要從您的視圖致電服務器驗證方法),然後簡單地說,

[Remote("action name", "controller name", HttpMethod = "POST")] 

它會通過AJAX調用來調用操作方法。你需要在你的視圖中添加Jquery Validation。

0
You need to decorate your properties with validation attribute.You can have muliple validation on single propery as shown below:- 
[Required(ErrorMessage = "Please enter Mobile")] 
[RegularExpression(@"^([7-9][0-9]*)$", ErrorMessage = "Should be numbers only starting with 7,8 or 9")] 
[StringLength(10, ErrorMessage = "Mobile should be of Max Length 10 Characters only")] 
public string Mobile{ get; set; } 
相關問題