Nick Gilbert Nick Gilbert - 27 days ago 8
ASP.NET (C#) Question

Implementing a Simple Search Function in ASP.NET MVC

I'm trying to implement a basic search page in the web app I'm developing. Right now the page looks like this

enter image description here

When a user enters a last name, the controller gets called to search the backend Microsoft SQL Server database for all accounts with that Last name

Right now the HTML form looks like this

@using (Html.BeginForm("SearchAct", "HomeController", FormMethod.Post))
{
<form>
<div>
Last Name:<br>
<input type="text" id="nameToFind">

<input type="button" id="submitId" value="submit" />

</div>
</form>
}


It's supposed to call this controller

[HttpPost]
public void SearchAct()
{
Console.WriteLine();
}


which will eventually execute the search and then put the results on the page. However, I can't get the controller to be called. I set a break point on the WriteLine so I know its never getting there and I don't know what I'm doing wrong

Answer

Add name attribute to your text box. Form collection build based on only name attributes.

Change button type to submit, then it will post your form to controller.

@using (Html.BeginForm("SearchAct", "Home", FormMethod.Post))
{

    <div>
        Last Name:<br>
        <input type="text" id="nameToFind" name="nameToFind">

        <input type="submit" id="submitId" value="submit" />

    </div>

}

@{
    if(ViewBag.SearchKey != null)
    {
        <span>
            Search Key: @ViewBag.SearchKey
        </span>
    }
}

Instead on Console.WriteLine() use ViewBag to send your required data back to view Refer below actions

//Get Action for rendering view
public ActionResult SearchAct()
{
    return View();
}


[HttpPost]
public ActionResult SearchAct(string nameToFind)
{
    ViewBag.SearchKey = nameToFind;

    return View();
}

Action parameter name and text box name attribute value must be same otherwise it will null

If your form contains multiple text box then read all input values form FromCollection or Request

[HttpPost]
public ActionResult SearchAct(FormCollection form)
{
    ViewBag.SearchKey = form["nameToFind"];

    return View();
}