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/Sear开发者_StackOverflow中文版chResult
[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 ViewData
object then only show on the view it if is not null
.
Very similar to this question MVC 3 form post and persisting model data
For this instance it looks like you are not passing the results to your partial view. Try this?
@{ Html.RenderPartial("SearchResults", Model.Results);
Since you are not persisting your search information using a model, the search information will be lost when the search form is posted.
Given your design and stated goal, it would be best to convert the form in your Index view into an Ajax form, then your controller can send your partial view back to populate a div below your Ajax form.
counsellorben
精彩评论