I'm trying to generate a list on user selection with the help of json in MVC. On page load the list will contain all the images but when the user clicks a link specifying a particular image group. Then images in that group should be shown only.
The problem is however all the images are loaded successfully on page. When I click the linkbutton for particular group it gives me a Json string with that group and redirects to Json actionresult.
Please help I'm very new to using Json.
Razor View:-
@foreach (var item in Model.ImageObj)
{
using (Html.BeginForm("getImageClick", "Home", new { grp = item.ImgGroup }))
{
<button class="btn btn-sm" type="submit" value="@item.ImgGroup" onclick="getImageClick()">@item.ImgGroup </button>
}
}
<div class="clearfix"></div>
</div>
<div class="table-bordered" style="margin-top:40px"></div>
<div class="container" style="margin-top:10px">
<div id="status" style="font-size:20px"></div>
<table id="tbl" class="table table-responsive table-hover table-bordered text-center" style="font-size:20px"></table>
<script language="javascript">
$("#status").text("Loading...");
$.get("getImage", null, BindData);
function BindData(Images) {
var tbl = $("#tbl");
for (var j = 0; j <= Images.length; j++) {
var newRow =
"<tr class='col-lg-4 col-md-4 col-sm-12'>" +
"<td>" + "<img src=/images/" + Images[j].Image + " " + 'alt="' + Images[j].Alt + '"' + 'style="width:200px; height:200px"' + 'class="img-thumbnail"' + " />" + "<br />" + Images[j].Description + "</td>" +
"</tr>"
;
tbl.append(newRow);
}
$("#status").text("Loaded");
}
$.get("getImageClick", null, BindDataNew);
function BindDataNew(ImagesNew) {
var tbl = $("#tbl");
for (var j = 0; j <= ImagesNew.length; j++) {
var newRow =
"<tr class='col-lg-4 col-md-4 col-sm-12'>" +
"<td>" + "<img src=/images/" + ImagesNew[j].Image + " " + 'alt="' + ImagesNew[j].Alt + '"' + 'style="width:200px; height:200px"' + 'class="img-thumbnail"' + " />" + "<br />" + ImagesNew[j].Description + "</td>" +
"</tr>"
;
tbl.append(newRow);
}
$("#status").text("Loaded");
}
</script>
Controller Methods:-
public ActionResult getImage()
{
Thread.Sleep(4000);
List<ImageTbl> Images = DbContext.ImageTbls.ToList<ImageTbl>();
return Json(Images, JsonRequestBehavior.AllowGet);
}
public ActionResult getImageClick(string grp)
{
Thread.Sleep(4000);
List<ImageTbl> ImagesNew = DbContext.ImageTbls.Where(x => x.ImgGroup == grp).ToList<ImageTbl>();
return Json(ImagesNew, JsonRequestBehavior.AllowGet);
}
What I have tried:
Added above the controller method and razor views.