Adrian Reszka Adrian Reszka -4 years ago 104
ASP.NET (C#) Question

Asp.Net MVC 4 adding search string as id parameter

I have created a simple site where user can search some things using id (always returns only 1 result) and I would like to add this search input as id to the URL. So that you can share URL to this specific search result.

It would look something like

Mysite/ProductSearch/12345


I do not know how to pass the id to the URL parameter and run the search for this id on link entry.

I would appreciate any tips and references.

Controller (ProductStateLookup) :

[HttpPost]
public ActionResult Index(string Search)
{
// some code to query the db and return me model with data
return View(model);
}


View :

<div id="ProductSearch">
<form action="ProductStateLookup/Index" method="POST">
<input type="text" name="Search" placeholder="Enter Product ID">
<input type="submit" value="Check P">
</form>
</div>

Answer Source

You need to make the method a [HttpGet] and change the <form> to method="GET".

public ActionResult Index(string Search)

View

@using (Html.BeginForm("Index", "ProductStateLookup", FormMethod.Get))
{
    <input type="text" name="Search" placeholder="Enter Product ID">
    <input type="submit" value="Check P">
}

Note that this will add a query string to the url (i.e. ../ProductStateLookup/Index?search=1234), unless you either add a custom route definition, or change the parameter and the textbox name attribute to id. A custom route definition would need to be something like

routes.MapRoute(
    name: "Search",
    url: "ProductStateLookup/{search}",
    defaults: new { controller = "ProductStateLookup", action = "Index", id = UrlParameter.Optional }
);

which would generate .../ProductStateLookup/1234

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download