首页 > 代码库 > 在控制器获取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种方法