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.Data;
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 JsonResult GetFruitName(string id)
{
string procedureName = "dbo.GetFruitName @FruitId, @FruitName OUT";
SqlParameter sqlParameter = new SqlParameter("@FruitId", id);
var sqlParameterOut = new SqlParameter
{
ParameterName = "@FruitName",
DbType = DbType.String,
Size = 30,
Direction = ParameterDirection.Output
};
var fruit = Context.Database.ExecuteSqlCommand(procedureName, sqlParameter, sqlParameterOut);
string name = Convert.ToString(sqlParameterOut.Value);
return Json(name);
}
[HttpPost]
public ActionResult Index(Fruit fruit)
{
ViewBag.Message = "Name: " + fruit.FruitName + " Id: " + fruit.FruitId;
return View();
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Procedure_OutParameter_Core_MVC.Models.Fruit
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#txtId").on('keyup', function () {
if ($(this).val() != '') {
$('#hfId').val($(this).val());
$.ajax({
url: '/Home/GetFruitName/',
data: { "id": $(this).val() },
type: "POST",
success: function (data) {
$('#hfName').val(data);
$('#lblName').html(data);
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
});
});
</script>
<form asp-action="Index" asp-controller="Home" method="post">
Id: <input type="text" id="txtId" name="fruitId" />
<br />
Name: <span type="text" id="lblName" name="fruitId"></span>
<input type="hidden" id="hfId" asp-for="FruitId" />
<input type="hidden" id="hfName" asp-for="FruitName" />
<br /><br />
<input type="submit" id="btnSubmit" value="Submit" />
<br /><br />
@ViewBag.Message
</form>
</body>
</html>
Screeenshot