2

I am using ASP.NET and MVC 3 in visual studio and have a question about passing an object from one action method(called Search) to another(called SearchResult). I tried using ViewData but it didnt persist down to the View of SearchResult. Below is a snippet of my code, from within a single controller. 'Search' gets called when data has been collected from a form and submit has been called(hence the [HttpPost] declaration):

[HttpPost]
public ActionResult Search(Search_q Q){
 // do some work here, come up with an object of type 'Search_a' 
 // called 'search_answer'.
ViewData["search_answer"] = search_answer;
return RedirectToAction("SearchResults");
}

public ActionResult SearchResult(Search_a answer)
{   
return View(answer);
}

I also tried using RedirectToAction("SearchResults", new {answer = search_answer}); instead of the above call to RedirectToAction but my 'search_answer' still didnt persist to the View. What is the best way to send this Search_a object to the SearchResult View?

2 Answers 2

8

You can use TempData to pass the object.

[HttpPost]
public ActionResult Search(Search_q Q){
    // do some work here, come up with an object of type 'Search_a' 
     // called 'search_answer'.
     TempData["search_answer"] = search_answer;
     return RedirectToAction("SearchResult");
}

public ActionResult SearchResult()
{
    var answer = (Search_a)TempData["search_answer"];   
    return View(answer);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked well, Thanks Eranga. One potential pitfall is that the object can be disposed before it gets used in the view if you have a overridden definition for Dispose in your controller(something VS tends to add in with its auto generated CRUD code).
1

If TempData does not suffice (what Eranga suggested), because SearchResult is not somewhat dependent on a Redirect (though you can have checks to get around it), you might want to look at the Request object. You can likely store the data as one of the query parameters via Request.Params. This can take advantage of the ModelBinding filter chain that Asp MVC has.

2 Comments

thanks I appreciate the suggestion, ill look up the Request Object!
Response.Params is read only - msdn.microsoft.com/en-us/library/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.