tags:

views:

89

answers:

5

I am creating a search page, the user types in the textbox and click 'Search', the controller takes the FormCollection in its Action method.

I do the search and return the results to the view however I want to return what the user searched for to the view. Is the TempData the best place for this or is this a risk?

+4  A: 

TempData is primarily used when the result of an action is a redirect to another action, and you need to keep some state around.

All you need to do is add another entry to the ViewData dictionary with "what the user searched for". Something roughly like this:

public ActionResult Search(FormCollection form) 
{
  // search algorithm

  ViewData["keywords"] = form["keywords"];
  return View();
}
gWiz
+2  A: 

The TempData is if you need that item the next time the user requests something else. Using the ViewData is what you're looking for. Also remember, the value he/she searched for is still available in the View as Request[searchBoxName].

Yuriy Faktorovich
+6  A: 

I'd say that your model for the results view should contain both the results and the search criteria.

Examples:

public class ResultsViewModel
{
     public SearchModel SearchCriteria { get; set; }
     ...
}

public class SearchModel
{
     public string Category { get; set; }
     ...
}

then, just populate the SearchCriteria in your results view model and you can retrieve it from there.

This assumes that your results view is strongly typed to ResultsViewModel.

tvanfosson
Yeah, this is how to do it if you are strictly adhering to strong-typing to pass data to the view.
gWiz
+1 @tv. I find the fact that people are still using ViewData for these types of things confusing. It's great for the name of an application, or static data like that, but for live changeable stuff?
griegs
+1  A: 

Using both the suggestions above will work, however it is better practice to add the data you need into the model than passing it via the ViewData.

If you pass it in the model then you get the advantages of it being strongly typed and remove the need to add logic to cast the ViewData entry into your view.

Dan Hedges
+1  A: 

Create a strongly typed view using a view model that will pass all the information you want on to the view and encode all user imputed information.

 public class ResultsSetViewModel
{
    public string Query { get; set; }

    public IList<Result> Results { get; set; }
}

Encode the user imputed data.

<h3>Search Results For: <%=Html.Encode(Model.Query) %></h3>
Aaron