Hi rani,
Using the article table and procedure i have created the example.
Check this example. Now please take its reference and correct your code.
Model
public class Fruit
{
public string FruitId { get; set; }
public string FruitName { get; set; }
}
Namespaces
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
Controller
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(string fruitId)
{
string procedureName = "dbo.GetFruitName @FruitId, @FruitName OUT";
SqlParameter parm1 = new SqlParameter("@FruitId", fruitId);
SqlParameter parm2 = new SqlParameter
{
ParameterName = "@FruitName",
DbType = DbType.String,
Size = 30,
Direction = ParameterDirection.Output
};
List<SqlParameter> sqlParameters = new List<SqlParameter>();
sqlParameters.Add(parm1);
sqlParameters.Add(parm2);
var fruit = Context.Database.ExecuteSqlCommand(procedureName, sqlParameters);
string name = Convert.ToString(parm2.Value);
List<Fruit> fruits = new List<Fruit>();
using (DbCommand cmd = Context.Database.GetDbConnection().CreateCommand())
{
cmd.CommandText = "SELECT * FROM Fruits WHERE FruitName = @Name";
DbParameter param = cmd.CreateParameter();
param.ParameterName = "@Name";
param.Value = name;
cmd.Parameters.Add(param);
Context.Database.OpenConnection();
using (DbDataReader ddr = cmd.ExecuteReader())
{
while (ddr.Read())
{
fruits.Add(new Fruit
{
FruitId = ddr["FruitId"].ToString(),
FruitName = ddr["FruitName"].ToString()
});
}
}
}
ViewBag.Fruits = fruits;
return View();
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Context_Database_ADO.Net_Core_MVC.Models.Fruit
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<form asp-action="Index" asp-controller="Home" method="post">
Fruit Id: <input type="text" id="txtId" name="fruitId" />
<input type="submit" id="btnSubmit" value="Submit" />
</form>
@if (ViewBag.Fruits != null)
{
<hr />
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
@foreach (var item in ViewBag.Fruits)
{
<tr>
<td>@item.FruitId</td>
<td>@item.FruitName</td>
</tr>
}
</tbody>
</table>
}
</body>
</html>
Screenshot