Search code examples
c#asp.netasp.net-mvcsql-server-2014

Simple Search / Filter Function to Database (ASP.NET MVC) (SQL Server 2014)


I would like to add a simple search function in my simple database.

I have completed an add, edit & delete function. I have difficulty dealing with the search function.

Currently I have a search box and I have thought of the proper SQL query to execute in the database so I can get a simple result.

I have difficulty in passing the textbox field to the controller so that it can be used as search query in the SQL Database, and then bringing it back to the view for the search results.

I am an ASP.NET MVC beginner. Please help. Thank you very much!

Here is my work so far:

View

@model IEnumerable<SampleReg.Models.Course>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@using (Html.BeginForm("Search", "Course", FormMethod.Post))
{
     <input type="text" name="txtsearch" value=" " />
     <input type="submit" name="btnsubmit" value="submit" />
}
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.crs_ID)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.crs_Course)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.crs_Major)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.crs_Spec)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.crs_ID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.crs_Course)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.crs_Major)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.crs_Spec)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.crs_ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.crs_ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.crs_ID })
            </td>
        </tr>
    }

</table>

Controller

public ActionResult Index()
{
    return View(GetAllCourse(""));
}

 [HttpPost, ActionName("Search")]
 [ValidateAntiForgeryToken]
 public ActionResult Search(string GetAllCourse) {
 string search = Request.Form["txtsearch"].ToString();
 //GetAllCourse("search");
     return View();
 }

 #region PRIVATE FUNCTIONS
 private List<Course> GetAllCourse(string search)
 {
     //DECLARATION AND INIT
     SqlConnection oCon = null;
     SqlCommand oCmd = null;
     SqlDataReader oDr = null;
     List<Course> oList = null;
     string SqlCon = @"Data Source=IT-MARICOR\LOCAL;Initial Catalog=INTERN;User ID=sa;Password=aaa";

     try
     {
         //SET CONNECTION
         oCon = new SqlConnection();
         oCon.ConnectionString = SqlCon;
         if (oCon.State == System.Data.ConnectionState.Closed)
         {
             oCon.Open();
         }

         //SET COMMAND
         oCmd = new SqlCommand();
         oCmd.Connection = oCon;
         oCmd.CommandType = System.Data.CommandType.Text;
         oCmd.CommandText = "SELECT * FROM Course " + (search == "" ? "" : " WHERE crs_Course LIKE '% " + search + "%'");

         oDr = oCmd.ExecuteReader();

         if (oDr.HasRows)
         {
             oList = new List<Course>();

             while (oDr.Read())
             {
                 Course oCourse = new Course();
                 oCourse.crs_ID = Convert.ToInt32(oDr["crs_ID"].ToString());
                 oCourse.crs_Course = oDr["crs_Course"].ToString();
                 oCourse.crs_Major = oDr["crs_Major"].ToString();
                 oCourse.crs_Spec = oDr["crs_Specialization"].ToString();
                 oList.Add(oCourse);
             }

             return oList;
         }
         return null;
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         //CLEAN UP RESOURCES
         oCon.Close();
         oCon = null;
     }

}
#endregion

Here is what it looks like: enter image description here


Solution

  • OR you can take help of jquery ajax method. give one id to text box.

    var Url = "/Course/Search",
    var textvalue= $('#textboxid').val(),
    $.ajax({
        url: Url ,
        data: { GetAllCourse: textvalue},
        type: "GET",
        url: Path,
        success: function (result) {
    
        }
    });