c# - 在 RedirectToAction MVC 中传递复杂对象

标签 c# asp.net-mvc

我知道这个问题已经被问过好几次并得到了回答,但没有一个解决方案对我有用。

这是我的 View 模型:

public class FlightSearchResults
{
    public FlightSearch SearchModel { get; set; }
    public List<vwLowFareSearchResults> SearchResults { get; set; }
    public string TestString { get; set; }
    public DateTime TestDate { get; set; }
}

我正在使用 RedirectToAction像这样:

FlightSearchResults flightSearchResults = new FlightSearchResults();
flightSearchResults.SearchModel = model;
flightSearchResults.SearchResults = flights;
flightSearchResults.TestDate = DateTime.Now.AddDays(-2);
flightSearchResults.TestString = "Just Testing . . .";
return RedirectToAction("index", "flights", flightSearchResults);

我只得到这个 List<vwLowFareSearchResults> SearchResults我的航类索引中的属性,其他人都没有分配值。我已经尝试了 StackOverFlow 上某些线程的几种变体,例如:

return RedirectToAction("index", "flights", new { SearchResults = flights, SearchModel = model });
return RedirectToAction("Result", "Dialog", new RouteValueDictionary(flightSearchResults));

我可以这样返回 View :

return View("~/Views/Flights/Index.cshtml", flightSearchResults);

但这不是一个好的解决方案,因为 url 没有更新。我正在修改一些旧项目,使用 Session 很麻烦和 Viewbag .

我需要简化之前代码中 View 和 Controller 数据通信的模式是一团糟。是否可以在不使用 ViewData 的情况下执行此操作?或 Viewbag在一个简单的 RedirectToAction .

如果我是 MVC 的新手,任何形式的帮助都将非常有用.

最佳答案

这是我最近使用的一种方法。尝试:-

        ... Previous code omitted.
        //In your controller action, save the data to TempData...
        TempData["FlightSearchResults"] = FlightSearchResults;

        return RedirectToAction("flights");
    }

    public ActionResult flights()
    {
        FlightSearchResults flightResults = TempData["FlightSearchResults"];

        return View(flightResults);
    }

我实际上使用 NewtonSoft 将对象序列化为字符串,然后再次回到目标操作中。所以你可能想尝试类似...

using Newtonsoft.Json;
...
...

        ... Previous code omitted.
        //In your controller action, save the data to TempData...
        TempData["FlightSearchResults"] = JsonConvert.SerializeObject(FlightSearchResults);

        return RedirectToAction("flights");
    }

    public ActionResult flights()
    {
        string storedResults = TempData["FlightSearchResults"].ToString();

        FlightSearchResults flightResults = JsonConvert.DeserializeObject<FlightSearchResults>(storedResults);

        return View(flightResults);
    }

关于c# - 在 RedirectToAction MVC 中传递复杂对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30284490/

相关文章:

C# System.Speech 未找到!

c# - 如何在不使用模型的情况下使用 Entity Framework 执行原始 SQL 查询?

c# - 无法将类型 'System.Collections.Generic.List<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<FirstApp.Model.TeamDetails>

asp.net-mvc - 注册通用页面基类

c# - 如何更改 TagHelpers 中 ModelExpression 的类类型?

c# - 如何编写基于验收的测试(从代码的角度来看)

javascript - 回发前mvc javascript确认不起作用

javascript - 将 JavaScript 变量传递给辅助方法

c# - 在循环内使用 .Where().FirstOrDefault() 时,ASP MVC 中的名称不唯一

c# - 使用partialview时刷新部分