基本类型的数据模型绑定
上节课我们讲解了如何传参到方法中接收,但是参数多的时候会发现参数会特别多,编码特别麻烦的问题,这节课说一下模型类的引入使用。
首先我们需要先在Models下创建一个Users.cs模型类,字段如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FirstProject.Models
{
public class Users
{
//string username,string pwd,int id,int age,string name
public string username{ get; set; }
public string pwd { get; set; }
public int id{ get; set; }
public int age{ get; set; }
public string name{ get; set; }
}
}对应的控制器Create方法代码:
using FirstProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace FirstProject.Controllers
{
public class UserController : Controller
{
// GET: User
public ActionResult Index()
{
return View();
}
//添加用户信息的功能
[HttpPost]
public ActionResult Create(Users u,int? a) //数据类型后加? 代表:当前值为可空类型,即不传参时可以为NULL,方法不会报错。如果说这个值不传参也不报错,也可以给默认值使用 int a = 10
{
return Content(u.username + "-" + u.pwd + "-" + u.id + "-" + u.age + "-" + u.name);
}
}
}对应的视图方法Index.cshtml代码:
@{
ViewBag.Title = "Index";
}
<h2>添加用户</h2>
<form action="/User/Create?id=1000" method="post">
<p>
用户名: <input type="text" name="username" value="" />
</p>
<p>
密码: <input type="password" name="pwd" value="" />
</p>
<p>
名字: <input type="text" name="name" value="" />
</p>
<p>
年龄: <input type="text" name="age" value="" />
</p>
<input type="submit" value="保存" />
</form>由于运行后的代码效果后前面的文章效果一致,在这里不做展示。
对数据模型数据的默认值设置和设置参数允许为空的设置。
【原因是,如果我们在控制器这里不加问号(?),代表这个参数值必填,如果不填就会报错。这时候可以对数据类型后面加?代表该值为可空类型设置】

运行后不传a的值报错:

加了问号后,就不会报错了。

1、在“ Index(string gname, int? gid)”方法的参数声明中,gid参数需要设定为int?类型,这种类型称为“可空 int类型”。
2、当文本框输入的内容包含“非int类型”或“空数据”时,模型绑定器将无法正确实现int类型转换,默认的绑定随之失效。为避免出现这类异常,需要为控制器的相关参数设定“可空类型”或“参数默认值”。
毕设系统定制、课程教学、问题1对1远程解答,可联系村长QQ:330168885
需要购买本课才能留言哦~