I am trying to achieve autocomplete feature that shows the matching data from db table when user inputs 2 letters in @html.textboxfor in razor page but keep getting 500 error every time I type input into textbox.

Here is my controller:

[HttpGet]
        public ActionResult PopulateUserInput(string input)
        {

            List<DataForm> studentList = new List<DataForm>();
            using (SqlConnection con = new SqlConnection(cnn))
            {
                con.Open();

                SqlCommand cmd = new SqlCommand("SELECT FirstName FROM table1 where FirstName like '@input' + '%'", con);
                cmd.Parameters.AddWithValue("@input", input);

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        DataForm studentData = new DataForm();
                        studentData.FirstName = Convert.ToString(reader["FirstName"]);
                        studentList.Add(studentData);
                    }
                }


            }

            return Json(studentList, System.Web.Mvc.JsonRequestBehavior.AllowGet);
        }

Here is my view page:

@using (Html.BeginForm("DataEntry", "DataForm", new { @class = "form-control", style = "display: flex;" }))
{
    @Html.AntiForgeryToken()

                @Html.TextBoxFor(m => m.FirstName,new { @id="firstName", @class = "form-control", tabindex = 1,@required = "required" })

}


@section Scripts {
    <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
$(function() {
                $("#firstName").autocomplete({
                    source: function (request, response) {
                        $.ajax({
                            url: '@Url.Action("PopulateUserInput", "DataForm")',
                            data: { input: request.term },
                            dataType: "json",
                            type: "GET",
                            success: function (data) {
                                response(data);
                            }
                        });

                },
                    minLength: 2 // Minimum characters before autocomplete starts 
                });
            });

</script>
    }

I even copied one of the data directly from the column into the textbox but it still returns 500 error. Where am I doing it wrong from my code? I would appreciate your help!

1

There are 1 best solutions below

8
Sain Pradeep On

Change your get method to post [HttpPost].

If you want to use as get method then you have to changes the method signature and read the data from query string.

public ActionResult PopulateUserInput()
{
   string input= this.Request.QueryString["input"];
           
   ...
}