Hi chetan,
Check this example. Now please take its reference and correct your code.
Model
public class ProductViewModel
{
public string ProductName { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
var products = new[] {
new { ID = 1, ProductName = "Chai" },
new { ID = 2, ProductName = "Chang" },
new { ID = 3, ProductName = "Aniseed Syrup" }
}.ToList();
ViewBag.GetProduct = products;
return View();
}
public ActionResult Viewoffer(int productid)
{
try
{
if (productid != 0)
{
var availableoffers = new[] {
new { ID = 1, productname="Chai", offername="Offer 1" },
new { ID = 1, productname="Chai", offername="Offer 4" },
new { ID = 2, productname="Chang", offername="Offer 2" },
new { ID = 2, productname="Chang", offername="Offer 5" },
new { ID = 3, productname="Aniseed Syrup", offername="Offer 3" },
new { ID = 3, productname="Aniseed Syrup", offername="Offer 6" }
};
var availableoffer = availableoffers.Where(x => x.ID == productid).ToList();
if (availableoffer != null)
{
ViewBag.offers = availableoffer;
}
}
return new JsonResult
{
Data = new { Success = true, ResultList = ViewBag.offers },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
catch (Exception ex)
{
return new JsonResult
{
Data = new { ErrorMessage = ex.Message, Success = false },
ContentEncoding = System.Text.Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.DenyGet
};
}
}
}
View
@model Product_Offer_MVC.Models.ProductViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h2>View offers</h2>
<div class="form-group">
<div class="col-md-10">
@Html.DropDownListFor(m => m.ProductName, new SelectList(ViewBag.GetProduct, "ID", "ProductName"),
"Select", new { @onchange = "DropDownProductList();", @id = "productid" })
</div>
</div>
<h3>Available Offers</h3>
<table id="tblOffers">
<thead>
<tr>
<th>Offer Name</th>
<th>Product Name</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function DropDownProductList() {
var DropDownSelectedValue = $("[id*=productid]").val();
$.ajax({
async: true,
type: 'GET',
dataType: 'JSON',
contentType: 'application/json;charset=utf-8',
data: { productid: DropDownSelectedValue },
url: '/Home/Viewoffer',
success: function (Data) {
$('#tblOffers tbody').empty();
if (Data.Success == true) {
var html = "";
for (var i = 0; i < Data.ResultList.length; i++) {
html += "<tr><td>"+Data.ResultList[i].offername+"</td>";
html += "<td>"+Data.ResultList[i].productname+"</td></tr>";
}
$('#tblOffers tbody').append(html);
}
},
error: function (r) {
alert("There is some issue.Error Occured");
}
});
}
</script>
</body>
</html>
Screenshot