AI智能
改变未来

ASP.NET 学习笔记(1)


ASP.NET 学习笔记

1. 服务端对客户端的通信

1)ViewBag

控制器

ViewBag.Content = \"这是controller里的数据\";

网页

@ViewBag.Content

2)ViewData

控制器

ViewData[\"Age\"] = 40;

网页

@ViewData[\"Age\"]

3) TempData

控制器

TempData[\"hello\"] = \"world\";

网页

@TempData[\"Age\"]

4) 通过model

控制器

public  ActionResult ShowData(){return View(\"ShowData2\",\"_Layout1\", new Models.Student(){Id = 1,Name = \"张三\",Age = 30});}

网页

@model  WebApplication4.Models.Student@*model里的数据类型一定要和View方法参数里的model类型一致*@@{ViewBag.Title = \"ShowData\";}<h2>ShowData</h2>@[email protected]@Model.Age

View方法

View(html页面,母版页,等等)

2. 客户端对服务端的通信

1)通过控制器中action的参数获取get和post数据

public ActionResult Index(string name){return Content(name);}

2)通过对象的方式,也就是model

public ActionResult Login(Models.LoginViewMode model){if (ModelState.IsValid){if (model.Email == \"admin\" && model.password == \"123\")return Content(\"ok\");elsereturn Content(\"wrong\");}

3. 客户端对服务端提交数据的校验

在model文件内

1)控制长度

[Required,StringLength(30,MinimumLength =2)]

2)要在控制器获取数据校验的结果

if (ModelState.IsValid){通过校验要做的事情}没通过校验做的事情

4. 一般分为两个action,一个负责显示页面用get,一个负责接收处理数据用post

[HttpGet]public  ActionResult Login(){return View();}[HttpPost][ValidateAntiForgeryToken]	//用于校验防伪时间戳public ActionResult Login(Models.LoginViewMode model){if (ModelState.IsValid){if (model.Email == \"admin\" && model.password == \"123\")return Content(\"ok\");elseModelState.AddModelError(\"\",\"账号密码错误\");//校验账号密码}else{return Content(\"buxing\");}}

5. model内的对html的设置

public class LoginViewMode{[Display(Name =\"电子邮箱\")]//html显示名字[EmailAddress(ErrorMessage =\"邮箱错误\")]//html的邮箱合理性校验以及自定义错误信息[Required,StringLength(30,MinimumLength =2)]public string Email { get;set;   }[Display(Name =\"密码\")][DataType(DataType.Password)]//html设置数据类型[Required,MinLength(6)]public string password { get; set; }}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » ASP.NET 学习笔记(1)