博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在控制器获取View数据的4种方法
阅读量:7212 次
发布时间:2019-06-29

本文共 2799 字,大约阅读时间需要 9 分钟。

  • 传统方法,通过name获取input的值
  • 通过 FormCollection 对象获取值
  • 通过参数获取
  • 构造对象,绑定数据对象

前台代码

Submit data @using (Ajax.BeginForm("SubmitData", "Home", new AjaxOptions {})) {
@Html.Label("Name") @Html.TextBox("txtName")
@Html.Label("Age") @Html.TextBox("txtAge")
}

界面显示

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
Submit data @using (Ajax.BeginForm("SubmitData", "Home", new AjaxOptions {})) {
@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name)
@Html.LabelFor(model => model.Age)
@Html.EditorFor(model => model.Age)
}

后台代码:

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,看了一些国外的文章写得很好,也很详细,就试着翻译一些自认为不错的文章,也当做自己的学习笔记

转载于:https://www.cnblogs.com/bryan2012/p/4081454.html

你可能感兴趣的文章
iOS网络层架构设计分享
查看>>
从 ReactiveCocoa 中能学到什么?不用此库也能学以致用
查看>>
linux上TCP connection timeout的原因查找
查看>>
DTMF的原理分析
查看>>
MODBUS-RTU通讯协议简介
查看>>
摄像机旋转约束问题及解决
查看>>
在.net中序列化读写xml方法的总结(转载)
查看>>
VC++ 使用CreateProcess创建新进程
查看>>
百度贴吧高考作文强贴
查看>>
管理 windows server 2003 的远程连接
查看>>
Apache+PHP 无法加载 MySql 模块的问题
查看>>
Leetcode: Design Hit Counter
查看>>
WPF中路由事件的传播
查看>>
ConfirmCancelUtilDialog【确认取消对话框封装类】
查看>>
FrameBuffer编程二(简单的程序上)
查看>>
Android应用开发实例篇(1)-----简易涂鸦板
查看>>
HUT-1694 零用钱 贪心
查看>>
ERP框架开发中的License许可验证机制设计与实现 (包含源代码下载)
查看>>
Log4j2使用总结
查看>>
Hibernate级联操作 注解
查看>>