首页 > 代码库 > 在控制器获取View数据的4种方法
在控制器获取View数据的4种方法
- 传统方法,通过name获取input的值
- 通过
FormCollection
对象获取值 - 通过参数获取
- 构造对象,绑定数据对象
前台代码
<fieldset> <legend>Submit data</legend> @using (Ajax.BeginForm("SubmitData", "Home", new AjaxOptions {})) { <div> @Html.Label("Name") @Html.TextBox("txtName") <br /> @Html.Label("Age") @Html.TextBox("txtAge") </div> <button>Submit</button> } </fieldset>
界面显示
1、传统方法,通过name获取input的值
[HttpPost] public ActionResult SubmitData() { string name = Request["txtName"].ToString(); int age = Convert.ToInt32(Request["txtAge"].ToString()); string result = "Name:" + name; result += "</br>" + "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 += "</br>" + "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 += "</br>" + "Age:" + age.ToString(); return Content(result); }
4、构造对象,绑定数据对象(这种是现在比较常用的方法)
前台代码:
@model mvcsample.Controllers.Person<fieldset> <legend>Submit data</legend> @using (Ajax.BeginForm("SubmitData", "Home", new AjaxOptions {})) { <div> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Age) </div> <div class="editor-field"> @Html.EditorFor(model => model.Age) </div> </div> <button>Submit</button> }</fieldset>
后台代码:
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 += "</br>" + "Age:" + age.ToString(); return Content(result); } } public class Person { public string Name { get; set; } public int Age { get; set; } }
最近在学一下MVC,看了一些国外的文章写得很好,也很详细,就试着翻译一些自认为不错的文章,也当做自己的学习笔记
在控制器获取View数据的4种方法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。