• MVC总结--数据传递


    • View—>Controller

          1.传统方式,Get方式提交。在Controller中获得client请求:

          string Name = Request["name"];

          string Id=Request .QueryString ["id"];

          2.超链接方式

          在超链接中传參,改进了原来的<a></a>

          <%:Html .ActionLink ("链接","Index","Home",new{id="1",name="Jim"}) %>

          上面的new{}。就是在传递一个參数集合,以这样的方式传过来的參数Controller怎样接收呢?

          假如是链接到Index页面。那么在Controller中的Index方法的參数中。这样写。这里的參数名称一定要和上述的參数名称一致。

           public ActionResult Index(int id,string name)

           {

                  return View();

           }

          也能够通过实体来获得

          public ActionResult Index(UserInfo user)

          {

                  return View();

          }

          仅仅是。实体中的属性也必须相应着:

          public class UserInfo

          {

                  public string id { get; set; }

                  public string name { get; set; }

          }

         3.Post:获得client提交的数据Request.Form

         4.在client建立表单。在Controller中获得表单集合FormCollection

         public ActionResult Index(FormCollection form1)

    • Controller—>View

         1.传统方式,直接输出:

         Response.Write(form1.Count );

         return Content("ok");

    • Controller<—>View

          1.通过ViewData

          ViewData是字典容器。它是key/Value键值集合

          在Controller中:

          ViewData["key"]

          在View中:

          <%=ViewData["key"]%>

          <%:ViewData["key"]%>

          或者让某个控件显示ViewData中的数据

          <%=Html .TextBox ("txtName") %>

          仅仅要key值同样,Controller和View中的ViewData中的数据就能够互相传递。

          2.强类型页面,设置视图模型

          弱类型页面传递的数据,没有限制,而强类型页面规定了该页面传递的数据类型--指定的某个模型(Model),能够使传递的数据准确,安全。为了让它们之间数据传递通畅无阻。须要我们在Controller中设定ViewData.Model类型。

          在页面上我们也要设定:

           <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcDemo1.Models.TDepartment>" %>

                                   

          然后在页面中就能够获得模型中详细字段。<%: Html.DisplayNameFor(model => model.txtName) %>

          这里"model"就是一个变量名。能够随意命名。由于在整个页面已经规定了类型了,所以也能够写成。

          <%: Html.DisplayNameFor(m => m.txtName) %>

    • 总结

          MVC中的数据传递看起来方便,安全,当然也有非常多约束。如一些參数名称的相应,除了以上方式,还有ViewBag等传递数据的方式,须要我们在实际应用中来比較它们各自的优劣。

  • 相关阅读:
    乌龟git
    CI的model层的操作
    排序算法
    linux安装教程
    linux命令Netstat
    linux压缩和解压缩
    标准库模块time,datetime
    为什么计算机时间和众多编程语言要从1970年1月1日开始算起
    模块和包的导入
    Python封装应用程序的最佳项目结构是什么?
  • 原文地址:https://www.cnblogs.com/yxysuanfa/p/6781551.html
Copyright © 2020-2023  润新知