Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing model and parameter with RedirectToAction

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.

This is my Search action :

public ActionResult Search(string culture, HotelSearchModel hotelSearchModel)
{ 
    // ...
}
like image 400
user1688401 Avatar asked May 09 '13 17:05

user1688401


People also ask

Can we pass model in RedirectToAction?

By including a NuGet package called MvcContrib you can easily pass model or form data through a simple RedirectToAction function call inside of your controllers.

How pass multiple parameters in RedirectToAction in MVC?

Second, to pass multiple parameters that the controller method expects, create a new instance of RouteValueDictionary and set the name/value pairs to pass to the method. Finally call RedirectToAction(), specifying the method name, controller name, and route values dictionary.

Which is correct syntax for RedirectToAction?

return RedirectToAction("Action", new { id = 99 }); This will cause a redirect to Site/Controller/Action/99. No need for temp or any kind of view data.


1 Answers

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

What you need to is save it in 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:

public ActionResult Search(string culture, HotelSearchModel hotelSearchModel)
{
    var obj = TempData["myObj"];
    hotelSearchModel = obj.hotelSearchModel;
    culture = obj.culture;
}
like image 163
Kenneth Avatar answered Sep 21 '22 11:09

Kenneth