MVC中Action及VIew之间数据传递

MVC中Action及VIew之间数据传递

 

第一部分:ViewData,ViewBag,TempData

ViewData 是一个字典类型的dictionary...本质上是一个object类型

ViewBag 是动态类型dynamic

TempData 也是object类型的,可以在不同的Action之间传递,类似于Session,但是TempData的值在取了一次后则会自动删除

     TempData默认是使用Session来存储临时数据的,TempData中存放的数据只一次访问中有效,一次访问完后就会删除了的

demo:

 public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {

            string[] arrs = new String[]
            {
                "123","222","333"
            };

            ViewData["items"] = arrs;
            ViewBag.items = arrs;
            TempData["items"] = arrs;

            return View();
        }

        public ActionResult Test()
        {
            return View();
        }

    }

Index

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<h2>ViewData</h2>
@foreach (var ii in (string [])ViewData["items"])
{
    <p>@ii</p>
}

<h2>ViewBag</h2>
@foreach (var ii in ViewBag.items)
{
    <p>@ii</p>
}

Test

@{
    ViewBag.Title = "Test";
}

<h2>Test</h2>

<h2>TempData</h2>

@if (TempData["items"] != null) { 
    foreach (var item in (string [])TempData["items"])
{
    <p>@item</p>
}
}

 

第二部分:MVC中数据传递几种常见方式解析

1.Action传递给View

  ViewData,ViewBag,TempData,Session

****这几个传递方式的生命周期不同

****Action之间的传递也是通过TempData和Session

demo

controller:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcPassValue.Models;

namespace MvcPassValue.Areas.Admin.Controllers
{
    public class CustomerController : Controller
    {
        //
        // GET: /Admin/Customer/

        public static List<Customer> customerlist = new List<Customer>(){
            new Customer(){ Id=1,Name="zhang"},
            new Customer(){Id=2,Name="lisi"},
            new Customer(){Id=3, Name="ke"}
        };

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Search(string id)
        {
            //
            var list = customerlist.Find(u => u.Id == int.Parse(id));
            return View(list);
        }

        public ActionResult Delete(string id, string key)
        {
            if (key == "yes")
            {
                customerlist.RemoveAt(1);
                return RedirectToAction("List");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

        public ActionResult List()
        {
            var list = customerlist;
            return View(list);
        }

    }
}

search:

@model MvcPassValue.Models.Customer

@{
    ViewBag.Title = "Search";
}

<h2>Search</h2>

<fieldset>
    <legend>Customer</legend>

    <div class="display-label">
         @Html.DisplayNameFor(model => model.Name)
    </div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Name)
    </div>
</fieldset>
<p>
    @Html.ActionLink("Edit", "Edit", new { id=Model.Id }) |
    @Html.ActionLink("Back to List", "List")
</p>

list:

@model IEnumerable<MvcPassValue.Models.Customer>

@{
    ViewBag.Title = "List";
}

<h2>List</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Id)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id,key="yes" })
        </td>
    </tr>
}

</table>

 

2.View传递数据给Action

****Url传参结合路由

http://localhost:23347/Admin/customer/search/3?key=1

   @Html.ActionLink("Delete", "Delete", new { id=item.Id,key="yes" })
  public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces: new [] { "MvcPassValue.Controllers"}
            );
        }
 public ActionResult Delete(string id, string key)
        {
            if (key == "yes")
            {
                customerlist.RemoveAt(1);
                return RedirectToAction("List");
            }
            else
            {
                return RedirectToAction("Index");
            }
        }

 ****表单的回传

     [HttpGet]
        public ActionResult Create()
        {
            var customer = new Customer();
            return View(customer);
        }

        [HttpPost]
        public ActionResult Create(FormCollection form)
        {
            var customer = new Customer();
            customer.Id = int.Parse(form["Id"].ToString());
            customer.Name=form["Name"].ToString();
            customerlist.Add(customer);

            return RedirectToAction("list");
        }
@model MvcPassValue.Models.Customer

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm()) {
    <fieldset>
        <legend>Customer</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Id)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Id)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

 

3.Action之间数据传递

 

posted @ 2020-06-15 14:40  youguess  阅读(513)  评论(0编辑  收藏  举报