mvc @html.textboxfor 添加正则表示式,ASP.NET MVC 三层合作

编程入门 行业动态 更新时间:2024-10-09 23:18:53

mvc @html.textboxfor 添加<a href=https://www.elefans.com/category/jswz/34/1767706.html style=正则表示式,ASP.NET MVC 三层合作"/>

mvc @html.textboxfor 添加正则表示式,ASP.NET MVC 三层合作

首先我们在M层创建一个类:

usingSystem;

usingSystem.Collections.Generic;

usingSystem.ComponentModel.DataAnnotations;

usingSystem.Linq;

usingSystem.Web;

namespaceWebApplication1.Models

{

publicclassGuestResponse

{

//数据验证,必填项,如果不填ErrorMessage请输入你的用户名

[Required(ErrorMessage="请输入你的用户名!")]

publicstringName{get;set;}

//同上

[Required(ErrorMessage="请输入邮箱")]

//正则表达式,判断是否是邮箱格式

[RegularExpression(".+\\@.+\\..+",

ErrorMessage="请输入正确的邮箱格式")]

publicstringEmail{get;set;}

//同上

[Required(ErrorMessage="请输入你的手机号码")]

publicstringPhone{get;set;}

publicbool?WillAttend{get;set;}

}

}

代码中已有注释,不多说。

下面,V层:

@modelWebApplication1.Models.GuestResponse

@{

Layout=null;

}

RsvpForm

@using(Html.BeginForm())

{

@Html.ValidationSummary()

Yourname:@Html.TextBoxFor(x=>x.Name)

Youremail:@Html.TextBoxFor(x=>x.Email)

Yourphone:@Html.TextBoxFor(x=>x.Phone)

Willyouattend?

@Html.DropDownListFor(x=>x.WillAttend,new[]{

newSelectListItem(){Text="Yes,I'llbethere",

Value=bool.TrueString},

newSelectListItem(){Text="No,Ican'tcome",

Value=bool.FalseString}

},"Chooseanoption")

}

这里注意第一行,

@modelWebApplication1.Models.GuestResponse

我们绑定我们写的数据类,这样我们才能顺利创建表单。

然后是C层:

[HttpGet]

publicViewResultRsvpForm(){

returnView();

}

[HttpPost]

publicViewResultRsvpForm(GuestResponsemodel)

{

if(ModelState.IsValid)

{

//TODO:Emailresponsetothepartyorganizer

returnView("Thanks",model);

}

else

{

//thereisavalidationerror

returnView();

}

}

这里我们有两个RsvpForm,我们在上面添加提交方式,分别是Get和Post

if(ModelState.IsValid)

是否通过数据验证,通过返回视图Thanks,且把表单传过来的值传给Thanks视图

数据验证不通过,返回原视图,

这里注意V层

@Html.ValidationSummary()

添加这句话,在数据验证的时候,数据不通过,视图层才能显示我们的错误提示信息。

本文转载自中文网

更多推荐

mvc @html.textboxfor 添加正则表示式,ASP.NET MVC 三层合作

本文发布于:2024-02-10 22:32:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1677682.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正则   textboxfor   html   mvc   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!