Reputation: 44673
I am working with mvc4 and have a field where a user can enter some text in to an input field which gets passed to the url and redirect to another page eg. /search/<>
My form is as follows but redirects as query string.
<form class="search" action="@Url.Action("Index", "Search")">
<div>
<input name="q" value="" type="search" />
<input type="image" name="btn" value="search" src="@Url.Content("/image1.jpg")" />
</div>
</form>
Any idea how I could alter my form to pass the inputed value to input "q" to the url.
Upvotes: 2
Views: 11248
Reputation: 1
public ActionResult Search(string query)
{
if (string.IsNullOrEmpty(query) == false)
return RedirectToAction("ACTION NAME",query);//prepend your action name
else
return RedirectToAction("Index");
}
Upvotes: 0
Reputation: 1039588
You could use a GET
method:
<form class="search" action="@Url.Action("Index", "Search")" method="get">
<div>
<input name="q" value="" type="search" />
<input type="image" name="btn" value="search" src="@Url.Content("~/image1.jpg")" />
</div>
</form>
You could also generate this exact same markup using the Html.BeginForm
helper which is designed for this purpose:
@using (Html.BeginForm("Index", "Search", FormMethod.Get, new { @class = "search" }))
{
<div>
<input name="q" value="" type="search" />
<input type="image" name="btn" value="search" src="@Url.Content("~/image1.jpg")" />
</div>
}
When you use the GET method all input element values will be sent in the query string when the form is submitted.
And if you want to append the search string in the path portion of the url instead of using a query string parameter I invite you to read the following blog post
from Scott Hanselman. I will quote only his conclusion:
After ALL this effort to get crazy stuff in the Request Path, it's worth mentioning that simply keeping the values as a part of the Query String (remember WAY back at the beginning of this post?) is easier, cleaner, more flexible, and more secure.
Upvotes: 3
Reputation: 4210
your Index view should look like
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Search", "Home"))
{
@Html.TextBox("query")
}
and your HomeController like
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Search(string query)
{
if (string.IsNullOrEmpty(query) == false)
return RedirectToAction(query);
else
return RedirectToAction("Index");
}
}
Upvotes: 0