模型绑定基础
绑定方式
-
手动绑定
使用Request请求获取
Request.Form:获取表单提交的值
RouteData.Value:获取路由的值
Request.QueryString:获取URL的值
Request.Files:获取上传的文件 -
模型绑定
直接从参数入手,(方法重载)又称隐式模型绑定(书上例子是创类(数据建模自动创类),以类的对象为参数)
案例:
- 手动绑定
视图:
@using (Html.BeginForm())
{
<p>编号:@Html.TextBox("Id")</p>
<br />
<p>姓名:@Html.TextBox("Name")</p>
<br />
<input type="submit" id="Submit1" value="提交" />
<br />
@ViewBag.Desc
}
控制器:
public ActionResult Index()
{
if (Request.Form.Count > 0)
{
var a = Request.Form["Id"];
var b = Request["Name"];
ViewBag.Desc = a + "喵了个咪" + b;
}
return View();
}
PS:执行顺序是:控制器→视图→模板页
- 模型绑定
控制器:方法重载(懒得数据建模,就直接传string参数了)
[HttpPost]
public ActionResult Index(string id, string ? name)
{
ViewBag.Desc = id + "喵了个咪" + name;
return View();
}
PS:参数中加个?表示即可为参数类型的值又可为null值
文件上传
控制器:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null)
{
if (file.ContentLength != 0)
{
file.SaveAs(Server.MapPath(".") + "/imanges/" + file.FileName);
return Content("<script>alert('添加成功')</script>");
}
}
return View();
}
视图:
<h2>案例</h2>
@using (Html.BeginForm("Index", "Default1", FormMethod.Post, new { enctype = "multipart/form-data" })) @*第四个参数中enctyoe的属性值必须为multipart/form-data,否则只会传文件名而不是文件本身*@
{
<input type="file" name="file" />
<input type="submit" />
}
模型验证
类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations; //需要引用
namespace MvcApplication1.Models
{
public class StuInfo
{
public int ID { get; set; }
[Display(Name = "姓名")] //设置要显示的字段名(中文别名)
[Required(ErrorMessage = "您需要填写{0}")] //设置为必填字段,已经错误提示
[StringLength(50, MinimumLength = 3)] //设置最大长度和最小长度
public string Name { get; set; }
[Display(Name = "年龄")]
[]
[Range(1, 150, ErrorMessage = "年龄填写不正确")] //设置值范围
public int Age { get; set; }
[Display(Name = "身高")]
[Range(typeof(decimal),"50.00","250.00",ErrorMessage="{0}超出指定范围")]
public decimal Height { get; set; }
[Display(Name = "生日")]
[DataType(DataType.Date)] //设置数据类型
public DateTime Birthday { get; set; }
[Display(Name = "电子邮箱")]
[RegularExpression(@"(\w)+(\.\w+)*@(\w)+((\.\w+)+)", ErrorMessage = "{0}格式不正确")] //正则验证
public string Email { get; set; }
}
}
视图:
<div>
<h1>添加学生信息</h1>
@using(Html.BeginForm())
{
<p>姓名:@Html.TextBox("Name")</p>
<p>年龄:@Html.TextBox("Age")</p>
<p>身高:@Html.TextBox("Height")</p>
<p>生日:@Html.TextBox("Birthday")</p>
<p>邮箱:@Html.TextBox("Email")</p>
<input id="Submit1" type="submit" value="提交"/>
@Html.ValidationSummary() //显示模型验证的提示信息
<p>@ViewBag.Info</p>
}
</div>
效果: