views:

189

answers:

1

I have a partial view that is a search textbox and button.

I am trying to make it a partial view so that I can render it in several places. When the user clicks search I want it to redirect to /Home/Search which will show a list of items based on what was put into the search box.

Is this the right approach or should I make the form just run the /Home/Search Index() action and not have a partial view controller at all?

Partial View

    <% using (Html.BeginForm("Search", "SearchBox")) {%>
                <%: Html.TextBoxFor(model => model.searchTerm) %>
                <input type="submit" value="Search" />
    <% } %>

Partial View Controller

  public class SearchBoxController : Controller
    {
        public ActionResult Search(ViewModels.SearchViewModel item)
        {
            Models.DataClasses1DataContext db = new Models.DataClasses1DataContext();
            List<Models.Item> retVal = (from p in db.Items
                                        where p.Name.Contains(item.searchTerm)
                                        select p).ToList();
            return RedirectToAction("Search", "Home"); //No data... What to do????
        }
    }
+2  A: 

or should I make the form just run the /Home/Search Index() action and not have a partial view controller at all?

Definitely yes. That's all, there is no real need for the partial controller, specially if it involves an extra redirect.

eglasius
Would this be the right way to implement this search control or is there a better way to go about it?
Blankasaurus
Its the way I've done and have worked very well for me, in both asp.net MVC and in regular asp.net (using simple form in that case). Taking out any unnecessary requests is always good. As for downsides, you can't drop it in a place in the view where you already have a form, not usually an issue with how one builds the views in MVC (at least I put the BeginForm near the fields). Note that you can still use the Html.BeginForm( syntax, just with the appropriate values to match the controller you want to call.
eglasius
btw, its pretty much self contained other than the obvious dependency to the search page (which you already have anyway). Additionally depending on how you want to work with it, you could have the form do a GET instead of a post, that's if you want to always have the search terms in the query string (like you usually do for paging) - like the google url used to be (now with the client side stuff they put it after # instead) / bing does.
eglasius