0

How would I take a text box value and use it in the query string on submit? I'd like it to start as this,

/News?favorites=True

and end up something like this after the user enters in a search and clicks search.

/News?query=test&favorites=True

The controller action looks like this

public ActionResult Index(string query,bool favorites)
{
   //search code   
}

This question is something close to what I'd like to do, but I'd like to use the query string and maintain the existing values in the query string.

Thanks.

2 Answers 2

5

Two possibilities:

  1. place the textbox inside a <form> with method="GET"
  2. use javascript to read the value and pass it to the server (with AJAX or window.location to perform a redirect)

Example with a <form>:

<% using (Html.BeginForm("index", "news", FormMethod.Get)) { %>
    <label for="query">Query:</label>
    <%= Html.TextBox("query") %>
    <input type="submit" value="Search" />
<% } %>

Example with javascript:

<label for="query">Query:</label>
<%= Html.TextBox("query") %>
<%= Html.ActionLink("Search", "index", "news", new { id = "search" }) %>

and then in a separate js file:

$(function() {
    $('#search').click(function() {
        var query = $('#query').val();
        // Here you could use AJAX instead of window.location if you wish
        window.location = this.href + '?query=' + encodeURIComponent(query);
        return false;
    });
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the quick response. Using the form tag is what I was looking for but the problem is that it wipes out any existing query params. With this method if the url was /News?favorites=True and I submit with the search, and exception is thrown(missing bool param), and the favorites is lost. Is there a way to keep the current params?
You could include the favorites parameter as hidden tag inside the form: <%=Html.Hidden("favorites") %>.
Awesome, thanks! Added <input type="hidden" name="favorites" value="<%=Request.QueryString["favorites"]%>" /> to the form tag and I'm good.
I'm glad you included encodeURIComponent, that's something easy to overlook when you're just looking for a quick fix (I almost did).
what if i want to show the search result inside a div element? @DarinDimitrov
0

Using Darin's above <form> answer but with Razor markup:

@using (Html.BeginForm("index", "news", FormMethod.Get)) 
{ 
<label for="query">Search:</label>
    @Html.TextBox("query")
<input type="submit" value="Search" />
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.