Asp. net calls background entity class data without refresh and returns it in Json format

  • 2021-08-31 07:42:10
  • OfStack

Create a new 1-class handler


public class Temp
{
  public int Index { get; set; }
  public string Description { get; set; }
  public string ImagePath { get; set; }
  public DateTime MyDate { get; set; }
}

// Data source  
 List<Temp> listTemp = new List<Temp>()
 {
   new Temp(){ Index=1,ImagePath="Desert.jpg", Description=" Picture 1",MyDate=DateTime.Now},
   new Temp(){Index=2,ImagePath="Chrysanthemum.jpg", Description=" Picture 2",MyDate=DateTime.Now},
   new Temp(){Index=3,ImagePath="Penguins.jpg", Description=" Picture 3",MyDate=DateTime.Now},
   new Temp(){Index=4,ImagePath="Jellyfish.jpg", Description=" Picture 4",MyDate=DateTime.Now},
   new Temp(){Index=5,ImagePath="Tulips.jpg", Description=" Picture 5",MyDate=DateTime.Now}
 };
 
 public void ProcessRequest(HttpContext context)
 {
   string index = context.Request["Index"];
   string jsonStr = string.Empty;
   foreach (var item in listTemp)
   {
     if (item.Index.ToString() == index)
     {
       JavaScriptSerializer serializer = new JavaScriptSerializer();
       jsonStr = serializer.Serialize(item); // Serialize json Format 
       break;
     }
   }
 
   context.Response.Write(jsonStr);
 }

Foreground JS code


$.getJSON("imageChange.ashx", { Index: i - 1 }, function (result) {
  $("#<%=lblDescription.ClientID %>").text(result.Description);
$("#<%=Image1.ClientID %>").attr("src", path + result.ImagePath.substr(result.ImagePath.lastIndexOf('/') + 1));
 
  var d = eval("new " + result.MyDate.replace(/\//g, ""));
          $("#<%=lblDate.ClientID %>").text(Todate(d.ToLocalTime().toString()));
});

Foreground JS code
//ToLocalTime () Converts UTC format data to standard date format
//Note that JavaScriptSerializer will convert the date serial number to the scale value since January 1, 1970, so the time value obtained by js needs some processing to convert it into standard date format
//See http://msdn.microsoft.com/zh-cn/library/system. web. script. serialization. javascriptserializer. aspx for details


Related articles: