使用RedirectToAction传递模型和参数

时间:2021-08-21 20:48:24

I want to send a string and a model (object) to another action.

我想将一个字符串和一个模型(对象)发送给另一个动作。

var hSM = new HotelSearchModel();
hSM.CityID = CityID;
hSM.StartAt = StartAt;
hSM.EndAt = EndAt;
hSM.AdultCount = AdultCount;
hSM.ChildCount = ChildCount;

return RedirectToAction("Search", new { culture = culture, hotelSearchModel = hSM });

When I use the new keyword it sends null object, although I set the objects hSm property.

当我使用new关键字时,它会发送null对象,尽管我设置了对象hSm属性。

This is my Search action :

这是我的搜索操作:

public ActionResult Search(string culture, HotelSearchModel hotelSearchModel)
{ 
    // ...
}

1 个解决方案

#1


13  

You can't send data with a RedirectAction. That's because you're doing a 301 redirection and that goes back to the client.

您无法使用RedirectAction发送数据。那是因为你正在进行301重定向,然后又回到客户端。

What you need to is save it in TempData:

你需要的是将它保存在TempData中:

var hSM = new HotelSearchModel();
hSM.CityID = CityID;
hSM.StartAt = StartAt;
hSM.EndAt = EndAt;
hSM.AdultCount = AdultCount;
hSM.ChildCount=ChildCount;
TempData["myObj"] = new { culture = culture,hotelSearchModel = hSM };

return RedirectToAction("Search");

After that you can retrieve again from the TempData:

之后,您可以从TempData中再次检索:

public ActionResult Search(string culture, HotelSearchModel hotelSearchModel)
{
    var obj = TempData["myObj"];
    hotelSearchModel = obj.hotelSearchModel;
    culture = obj.culture;
}

#1


13  

You can't send data with a RedirectAction. That's because you're doing a 301 redirection and that goes back to the client.

您无法使用RedirectAction发送数据。那是因为你正在进行301重定向,然后又回到客户端。

What you need to is save it in TempData:

你需要的是将它保存在TempData中:

var hSM = new HotelSearchModel();
hSM.CityID = CityID;
hSM.StartAt = StartAt;
hSM.EndAt = EndAt;
hSM.AdultCount = AdultCount;
hSM.ChildCount=ChildCount;
TempData["myObj"] = new { culture = culture,hotelSearchModel = hSM };

return RedirectToAction("Search");

After that you can retrieve again from the TempData:

之后,您可以从TempData中再次检索:

public ActionResult Search(string culture, HotelSearchModel hotelSearchModel)
{
    var obj = TempData["myObj"];
    hotelSearchModel = obj.hotelSearchModel;
    culture = obj.culture;
}