Suppose I have a simple search form with a textbox. And upon submitting the form I send the contents of the textbox to a stored procedure which returns to me the results. I want the results to be displayed on the same page the form was, except just below it.
Right now I’m doing the following but it’s not working out exactly the way 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 “SearchResults” View:
@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);
}
I can only seem to get the results to display on an entirely new page (not being embedded as a partial view), or I get an error when I load the search page because there are no results (since I hadn’t searched yet).
Is there any better way to achieve what I’m trying to do? I feel like I’m going against some of the best practices in MVC.
You could return the results in a
ViewDataobject then only show on the view it if isnot null.