- 传统方法,通过name获取input的值
- 通过
FormCollection
对象获取值 - 通过参数获取
- 构造对象,绑定数据对象
前台代码
界面显示
1、传统方法,通过name获取input的值
[HttpPost] public ActionResult SubmitData() { string name = Request["txtName"].ToString(); int age = Convert.ToInt32(Request["txtAge"].ToString()); string result = "Name:" + name; result += "" + "Age:" + age.ToString(); return Content(result); }
结果输出:
2、通过 FormCollection
对象获取值
[HttpPost] public ActionResult SubmitData(FormCollection form) { string name = form["txtName"].ToString(); int age = Convert.ToInt32(form["txtAge"].ToString()); string result = "Name:" + name; result += "" + "Age:" + age.ToString(); return Content(result); }
结果输出就不贴了
3、通过参数获取
[HttpPost] public ActionResult SubmitData(string txtName, string txtAge) { string name = txtName; int age = Convert.ToInt32(txtAge); string result = "Name:" + name; result += "" + "Age:" + age.ToString(); return Content(result); }
4、构造对象,绑定数据对象(这种是现在比较常用的方法)
前台代码:
@model mvcsample.Controllers.Person
后台代码:
public class HomeController : Controller { public ActionResult Index() { Person model = new Person(); return View(model); } [HttpPost] public ActionResult SubmitData(Person person) { string name = person.Name; int age = person.Age; string result = "Name:" + name; result += "" + "Age:" + age.ToString(); return Content(result); } } public class Person { public string Name { get; set; } public int Age { get; set; } }
最近在学一下MVC,看了一些国外的文章写得很好,也很详细,就试着翻译一些自认为不错的文章,也当做自己的学习笔记