vote up 2 vote down
star
4

Let's say I have a search page called Search.aspx that takes a search string as a url parameter ala Google (e.g. Search.aspx?q=This+is+my+search+string).

Currently, I have an asp:TextBox and an asp:Button on my page. I'm handling the button's OnClick event and redirecting in the codebehind file to Search.aspx?q=

What about with ASP.NET MVC when you don't have a codebehind to redirect with? Would you create a GET form element instead that would post to Search.aspx? Or would you handle the redirect in some other manner (e.g. jQuery event attached to the button)?

flag

3 Answers

vote up 3 vote down

You need to understand that MVC doesn't directly reference .aspx pages like WebForms in its URLs. Its main purpose is to separate concerns, that is model (data), controller (logic), and view (presentation).

First, you'd have to create a route matching your URLs, which would now look like this for example : /home/search/This+is+my+search+string

This would call the Search action method of the Home controller, which would get "This is my search string" as an input parameter. This action is responsible for accessing the model and pulling the results probably from a database.

Typically, your search action would then return a ViewResult containing the view placed in the folder /Views/Home/Search.aspx. Here, you can use neither the Postback functionality nor the events of your Web controls like in WebForms, because MVC applications are stateless and not event-driven. It's more like a request/dispatch way of doing things.

Read more about MVC here.

link|flag
vote up 0 vote down

You can use a simple javascript in the button's onclick to redirect to the search page:

Search <input type="text" id="go" size="4" /><input type="button" value="<%=Html.Encode(">>") %>" onclick="javascript:window.location='<%=Url.Action("Search", "Home") %>/' + document.getElementById('go').getAttribute('value')" />
link|flag
vote up 0 vote down

Create a user control called Search.ascx with a form:

<% using (Html.BeginForm ("Search", "Home")) { %>
    <input name="search" type="text" size="16" id="search" />
    <input type="image" name="search-image" id="search-image" src="search.gif" />
<% } %>

And in your search action all you need is the following:

public class HomeController : Controller
{
    public ActionResult Search (string search)
    {
        throw new Exception (string.Format ("Search: {0}", search));
    }
}

In your master page or wherever you can then add

<% Html.RenderPartial ("Search"); %>
link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.