Mvc中的資料驗證方法

2021-10-25 04:15:24 字數 1676 閱讀 9959

model**:注意其中加了驗證

using system;

using system.collections.generic;

using system.componentmodel.dataannotations;

using system.linq;

using system.web;

namespace mvcvalidatedemo.models

[stringlength(5

,errormessage=

"長度必須小於5")]

[required

(errormessage=

"*姓名必填")]

public

string username

[range(1

,100

,errormessage=

"*年齡必須在1-100之間")]

[required

(errormessage =

"*年齡必填")]

public

int age

}}

view檢視**:

@model mvcvalidatedemo.models.userinfo

@"~/scripts/jquery-1.8.2.js"

>

<

/script>

"~/scripts/jquery.validate.js"

>

<

/script>

<

!doctype html>

"viewport" content=

"width=device-width"

/>

add<

/title>

<

/head>

@using

(html.

beginform()

)@html.

actionlink

("back to list"

,"index"

)<

/div>

<

/body>

<

/html>

控制器**:

}在medol中加入驗證方法,在前端即可實現驗證功能,提交到控制器的add(userinfo userinfo)方法時,在後台判斷一下modelstate.isvalid即可,如果為true說明驗證通過,返回index檢視,如果為false則不通過!返回add檢視!

MVC資料驗證Model Validation

required必須項驗證屬性 required public string firstname id編號 scaffoldcolumn false required allowemptystrings false,errormessage 使用者id不能為空 display name 記錄編號 o...

MVC資料驗證Model Validation

required必須項驗證屬性 required public string firstname id編號 scaffoldcolumn false required allowemptystrings false,errormessage 使用者id不能為空 display name 記錄編號 o...

MVC前後臺驗證方法

mvc後台驗證 驗證特性 requied 必填驗證 compare比較驗證 stringlength字串的長度 range 數字 整數和浮點 時間等型別的資料範圍驗證 1 新增引用 usingsystem.componentmodel usingsystem.componentmodel.dataa...