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