zoukankan      html  css  js  c++  java
  • Asp.net MVC中 Controller 与 View之间的数据传递

    在ASP.NET MVC中,经常会在Controller与View之间传递数据

    1、Controller向View中传递数据

    (1)使用ViewData["user"]

    (2)使用ViewBag.user

    (3)使用TempData["user"]

    (4)使用Model(强类型)

    区别:

    (1)ViewData与TempData方式是弱类型的方式传递数据,而使用Model传递数据是强类型的方式。

    (2)ViewData与TempData是完全不同的数据类型,ViewData数据类型是ViewDataDictionary类的实例化对象,而TempData的数据类型是TempDataDictionary类的实例化对象。

    (3)TempData实际上保存在Session中,控制器每次请求时都会从Session中获取TempData数据并删除该Session。TempData数据只能在控制器中传递一次,其中的每个元素也只能被访问一次,访问之后会被自动删除。

    (4)ViewData只能在一个Action方法中进行设置,在相关的视图页面读取,只对当前视图有效。理论上,TempData应该可以在一个Action中设置,多个页面读取。但是,实际上TempData中的元素被访问一次以后就会被删除。

    (5)ViewBag和ViewData的区别:ViewBag 不再是字典的键值对结构,而是 dynamic 动态类型,它会在程序运行的时候动态解析。

    2、View向Controller传递数据

    在ASP.NET MVC中,将View中的数据传递到控制器中,主要通过发送表单的方式来实现。具体的方式有:

    (1)通过Request.Form读取表单数据

    View层:

    @using (Html.BeginForm("HelloModelTest", "Home", FormMethod.Post))
    {
        @Html.TextBox("Name");
        @Html.TextBox("Text");
        <input type="submit" value="提交" />
    }

    Controller:

         [HttpPost]
            public ActionResult HelloModelTest()
            {
                string name= Request.Form["Name"];
                string text= Request.Form["Text"];
                return View();
            }

    (2)通过FormCollection读取表单数据

    [HttpPost]
            public ActionResult HelloModelTest(FormCollection fc)
            {
                string name= fc["Name"];
                string text  = fc["Text"];
                return View();
            }

    (3)通过模型绑定

      1)、将页面的model直接引过来

    [HttpPost]
    public ActionResult HelloModelTest( HelloModel model)
    {
        // ...
    }

      2)、页面的元素要有name属性等于 name和text 的

     public ActionResult HelloModelTest( string name,string text)
    {
        // ….
    }

    (4)通过ajax方式,但是里面传递的参数要和Controller里面的参数名称一致

  • 相关阅读:
    C语言的标准输入输出
    Java 循环中标签的作用
    Java并发包中CountDownLatch的工作原理、使用示例
    Java并发包中CyclicBarrier的工作原理、使用示例
    Java并发包中Semaphore的工作原理、源码分析及使用示例
    ScheduleThreadPoolExecutor的工作原理与使用示例
    Java 循环中标签的作用
    线程池ThreadPoolExecutor、Executors参数详解与源代码分析
    线程池的工作原理及使用示例
    Callable、Future、RunnableFuture、FutureTask的原理及应用
  • 原文地址:https://www.cnblogs.com/ck168/p/5504951.html
Copyright © 2011-2022 走看看