MVC 模型绑定
Posted //我是小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MVC 模型绑定相关的知识,希望对你有一定的参考价值。
模型绑定是HTTP请求与C#方法之间的一个桥梁,它根据 Action 方法中的 Model 类型创建 .NET 对象,并将 HTTP 请求数据经过转换赋给该对象。
代码演示
首先创建Person类:
public class Person
{
public Person(){ }
public Person(string name, int age)
{
this.name = name;
this.age = age;
}
public string name { get; set; }
public int age { get; set; }
}
创建控制器代码如下:
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Person p)
{
ViewBag.msg = "欢迎您:" + p.name + ",您今年" + p.age + "岁了";
return View();
}
}
视图body代码:
<body>
<form method="post" action="Index">
<p>姓名:<input type="text" name="name"/></p>
<p>年龄:<input type="text" name="age"/></p>
<input type="submit" value="提交"/>
</form>
<div id="show">
<h2>@ViewBag.msg</h2>
</div>
</body>
效果:
以上是关于MVC 模型绑定的主要内容,如果未能解决你的问题,请参考以下文章