Home > Net >  Showing Jason Result data from for loop to view section
Showing Jason Result data from for loop to view section

Time:08-02

Just want to know that the following thing can be done by using Javascript - Ajax call.

In my ASP.NET MVC web application, there are posts that load on the home page created by users.

So like a Facebook post, it shows the Employee Name, Department, and the post (image) that he posts in this system.

This data collected code I wrote in the ActionResult in Home Controller.

But seems when It loads, the page loading time is increased.

to reduce the loading time now I have written this Ajax call and I tried to collect the data and pass it to the section where the post shows.

This is the code

function Announcements() {
 
  try {
    $.ajax({
      url: '../Home/Announcements',
      type: 'POST',
      dataType: 'json',
      cache: false,
      async: false,
      data: {},
      success: function (data) {
        if (data.Success == true) {
 
          for (var i = 0; i < data.Announcements; i  ) {
 
            alert("Annoncementsdadsa")
          }
 
          $("#Announcements").append(data.Announcements);
        }
      }
    });
  } catch (err) {
    console.log(err.message)
  }
}

This is the JsonResult

public JsonResult Announcements() {
  try {
    DateTime twoDaysAgo = DateTime.Today.AddDays(-1);
 
    List < NewsShareViewModel > smcNews = new List < NewsShareViewModel > ();
 
    smcNews = (from n in db.NewsShare join e in db.CreateEmployee on n.Created_By equals e.Id join d in db.CreateDepartment on e.DepId equals d.Id where n.CreatedDate > twoDaysAgo select new NewsShareViewModel {
      Id = n.Id,
        UserName = e.EmpName,
        Department = d.Department,
        Message = n.Comment,
        UserId = n.Created_By,
        CreatedDate = n.CreatedDate.ToString()
    }).ToList();
 
    return Json(new {
      Success = true,
        Announcements = smcNews
 
    }, JsonRequestBehavior.AllowGet);
 
  } catch (Exception ex) {
    return Json(new {
      Success = false, ErrorMessage = ex.Message
    }, JsonRequestBehavior.AllowGet);
  }
}

Here I'm returning the UserName,Department, Message, UserId, CreatedDate.

Those data are in the data.Announcements set and I want to pass the data to this view section.

@foreach (var item in RsmcNews) { <div >
   <div >
     <div >
       <img src="@Url.Action(" RetrieveImage","UserProfile", new { [email protected] })"  alt="User Image" one rror="this.src='/Addons/dist/img/Userdefault.jpg'">
       <span >
         <a href="#">@item.UserName</a>
       </span>
       <span >
         <a href="#">@item.Department</a>
       </span>
       <span >Shared publicly - @item.CreatedDate</span>
     </div>
     <!-- /.user-block -->
     <div >
       <button type="button"  data-card-widget="collapse">
         <i ></i>
       </button>
     </div>
     <!-- /.card-tools -->
   </div>
   <!-- /.card-header -->
   <div >
     <h5> @item.Message </h5>
     <img  src="@Url.Action(" RetrieveNews","NewsShares", new { [email protected] })" width="600" height="400" one rror="this.src='/Addons/dist/img/Userdefault.jpg'" sizes="50">
   </div>
 </div> 
}

So what I did earlier was in the ActionResult Index , I collect the data and pass it to the session. And from the session I pass it to RsmcNews variable and loaded on above section.

So want to know how to do the same with the Ajax Result.Summary of this is, Now Already data are there on the data.Announcements and need to know how to pass it to the section by separating UserName , Department etc

CodePudding user response:

You may access data members under Announcement like data.Announcements[i].UserName and data.Announcements[i].Department

You will need to use data.Announcements.length instead of data.Announcements in the for loop

You may create a new div for output

<div id="outputDiv"></div>

And update the view from ajax function

function Announcements() {

    try {
        $.ajax({
            url: '../Home/Announcements',
            type: 'POST',
            dataType: 'json',
            cache: false,
            async: false,
            data: {},
            success: function (data) {
                console.log(data);
                if (data.Success == true) {

                    for (var i = 0; i < data.Announcements.length; i  ) {
                        var card = $(".card").clone().appendTo($("#outputDiv"));
                        $(card).find(".username a").text(data.Announcements[i].UserName);
                        $(card).find(".description").text("Shared publicly - "   data.Announcements[i].CreatedDate);
                        $(card).find(".card-body h5").text(data.Announcements[i].Message);
                    }

                    $("#Announcements").append(data.Announcements);

                }
            }
        });
    } catch (err) {
        console.log(err.message)
    }
}
  • Related