Best way to display a search form and its results on the same page?

Suppose I have a simple search form with a text box. And after submitting the form, I submit the contents of the text field to a stored procedure that returns the results to me. I want the results to appear on the same page as on the form, but only below.

Now I am doing the following, but it doesn’t work out exactly as I want:

"Index" View of My SearchController

@using (Html.BeginForm("SearchResults", "Search", FormMethod.Post, new { @class = "searchform" }))`{ <fieldset> <legend>Name</legend> <div class="editor-label"> @Html.Label("Search") </div> <div class="editor-field"> @Html.TextBox("Name") </div> <input type="submit" value="Search" class="formbutton" /> </fieldset> @{ Html.RenderPartial("SearchResults", null); 

This is my view of "SearchResults":

 @model IEnumerable<MyProject.Models.spSearchName_Result> <table> @foreach (var item in Model) { <tr> <td> @item.Name </td> </tr> } </table> 

This is my controller:

  // GET: /Search/SearchResult [HttpPost] public ActionResult SearchResult(FormCollection collection) { var result = myentity.spSearchName(collection["Name"]); return PartialView("SearchResults", result); } 

It seems to me that the results can be displayed on a completely new page (without being embedded as a partial view), or I get an error when loading the search page because there are no results (since I did not have a search yet).

Is there a better way to achieve what I'm trying to do? I feel like I'm going against some of the best practices in MVC.

+4
source share
3 answers

You can return the results to a ViewData object and then show only on its representation if not null .

+3
source

Very similar to this question MVC 3 form post and persistent model data

In this case, it looks like you are not passing the results to a partial view. Try it?

 @{ Html.RenderPartial("SearchResults", Model.Results); 
+3
source

Since you do not save your search information using the model, the search information will be lost when submitting the search form.

Given your design and stated purpose, it would be best to convert the form as an index into an Ajax form, after which your controller can send your partial view back to fill in the div below your Ajax form.

counsellorben

+1
source

All Articles