how to call ashx file using ajax in asp.net

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

I m developing website. i want call one ashx file which return all process list on server

回答1:

Step: 1 Create the handler and the server side code like the following

<%@ WebHandler Language="C#" Class="Handler" %>

using System; using System.Web; using System.Linq; public class Handler : IHttpHandler {      public void ProcessRequest (HttpContext context) {         context.Response.ContentType = "application/json";          var processes = System.Diagnostics.Process.GetProcesses();         System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();         context.Response.Write(serializer.Serialize(processes.Select(p => p.ProcessName)));       }      public bool IsReusable {         get {             return false;         }     }  } 

Step 2: Give the necessary permissions for your asp.net process / application pool. In development version you can add the impersonation tag in the web.config as a shortcut.

<identity impersonate="true" userName="windows/usernamer" password="password"/> 

Step 3: Use the handler's result from the aspx page via ajax or otherwise. An example is as follows using the jquery library.

<%@ Page Title="Home Page" Language="CS" MasterPageFile="~/Site.Master" AutoEventWireup="false"     CodeFile="Default.aspx.cs" Inherits="_Default" %>  <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js">  </script> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">     <ul id="processes">      </ul>      <script type="text/javascript">         $(function () {             $.get("handler.ashx", function (data) {                 $.each(data, function (index, element) {                     $("#processes").append($("<li />").html(element));                 });             });         });         </script> </asp:Content> 

Hope this helps.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!