Filter Data using TextBox in ASP.Net Core MVC

samee
 
on Jun 09, 2022 06:19 AM
Sample_385989.zip
1404 Views

I have some student data like first Name, last Name, Hall Ticket Number, 5 subjects marks, total and percentage.

This data is coming from Microsoft SQL Server Management Studio. I want one input and one button if user enter Hall Ticket Number and click to button it will fetch the data from SQL Server and show all remaining detail of that student like first name, last name etc. in ASP.Net Core MVC.

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jun 10, 2022 02:53 AM

Hi samee,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Namespaces

using System.Data;
using System.Data.SqlClient;

Controller

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult Detail(string id)
    {
        string constr = @"Server=.\SQL2019;DataBase=Northwind;UID=sa;PWD=pass@123";
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employees WHERE EmployeeId = @Id", con))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    cmd.Parameters.AddWithValue("@Id", id);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    ViewBag.Data = dt;
                }
            }
        }

        return View();
    }
}

View

Index

@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body class="container">
    <form asp-controller="Home" asp-action="Detail" method="post">
        Employee Id: <input type="text" id="txtId" name="id" class="form-control" />
        <input type="submit" value="Submit" class="btn btn-primary" />
    </form>
</body>
</html>

Detail

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Detail</title>
</head>
<body>
    @if (ViewBag.Data != null)
    {
        System.Data.DataRow dr = ViewBag.Data.Rows[0];
        <span style="font-weight:bold">Name : </span>@string.Format("{0} {1}", dr["FirstName"], dr["LastName"]);
        <br />
        <span style="font-weight:bold">Country : </span>@dr["Country"].ToString();
    }
</body>
</html>

Screenshot