【问题标题】:Passing an object to another method and then the view将对象传递给另一个方法,然后是视图
【发布时间】:2016-12-08 19:59:02
【问题描述】:

所以我有这个索引方法:

 public List<ParkingLot> parkingLot;
 public async Task<ActionResult> Index(Position postData)
        {
            string json = new WebClient() { Encoding = Encoding.UTF8 }.DownloadString("json_url_removed_for_post");
            parkingLot = JsonConvert.DeserializeObject<List<ParkingLot>>(json);

            return View(parkingLot);
         }

我想将 ParkingLot 对象列表和接收到的 postData 都发送到 About 方法。

public ActionResult About()
        {
            ViewBag.Message = "hello about";

            return View();
        }

我该怎么做呢?然后我希望在 about 索引中能够显示一些数据。如何从控制器传递它?

【问题讨论】:

  • 不要使用TempData(在“关于”视图中刷新浏览器,看看会发生什么)

标签: c# asp.net-mvc parameter-passing


【解决方案1】:

你应该使用TempData:

public List<ParkingLot> parkingLot;
public async Task<ActionResult> Index(Position postData)
    {
        string json = new WebClient() { Encoding = Encoding.UTF8 }.DownloadString("json_url_removed_for_post");
        parkingLot = JsonConvert.DeserializeObject<List<ParkingLot>>(json);
        TempData["postData"] = postData;
        TempData["parkingLot"] = parkingLot;
        return View(parkingLot);
     }

然后,您可以同时使用它们:

public ActionResult About()
    {
        ViewBag.Message = "hello about";
        var postData = (Position)TempData["postData"];
        var parkingLot = (List<ParkingLot>)TempData["parkingLot"];
        return View();
    }

请注意,TempData 需要进行类型转换,因为将数据存储为objects,并检查null

你可以将postData返回到About页面,像这样:

return View(postData);

然后,在About页面的顶部,你必须写@model Position,然后你就可以使用它了,在Model类的帮助下。

【讨论】:

  • 看起来可行。现在如何在 About 视图中显示 postData.latitude?​​span>
  • @crystyxn 编辑了答案。
猜你喜欢
  • 1970-01-01
  • 2017-12-16
  • 2012-03-01
  • 1970-01-01
  • 2018-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多