我需要在ASP.net中创建一个按钮,我可以将其嵌入到另一个网页中。
本质上,按钮将在页面加载时查询数据库服务器端,然后根据查询的返回值更改它的图像。
有谁知道这方面的最佳方法?你可以告诉我,我不是ASP.net的专业人士。最好用C#编写。
答案 0 :(得分:1)
在这种情况下,我建议使用IHttpHandler
而不是通用的WebForm。 https://msdn.microsoft.com/en-us/library/system.web.ihttphandler(v=vs.110).aspx
处理程序更适合此请求,因为它能够快速响应,并且专门用于处理不一定基于HTML的特定请求。这可以非常简单地连接以接受请求,查询数据库并生成您选择的图像。现在,您还没有提供有关图像来源的详细信息,但我们可以查看一个简单的请求。
要从webforms网络应用程序开始,请选择我们将其命名为GenericHandler
的新DynamicImage.ashx
。这将构建我们的初始模板,如下所示。
public class DynamicImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
此模板提供了处理我们请求的基础知识。当请求到达时,WebServer将执行ProcessRequest()
方法作为参数传递HttpContext
。从这里我们可以用它来传达我们的回应。
对于参数sakes,我们假设我们根据代表我们数据库中用户的QueryString
参数username
来查询图像。我已经在您的步骤中包含了一些基本代码来实现此目的。 (代码评论)
public void ProcessRequest(HttpContext context)
{
//get our username from the query string
var username = context.Request.QueryString["username"];
//clear the response and set the content type headers
context.Response.Clear();
context.Response.ContentType = "image/png";
//if the username is empty then end the response with a 401 not found status code
if (string.IsNullOrWhiteSpace(username))
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//do a db query to validate the user. If not valid do a 401 not found
bool isValidUser = new UserManager().IsValidUser(username);
if (!isValidUser)
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//get the user image file path from a server directory. If not found end with 401 not found
string filePath = context.Server.MapPath(string.Format("~/App_Data/userimages/{0}.png", username));
if (!System.IO.File.Exists(filePath))
{
context.Response.StatusCode = 401;
context.Response.End();
return;
}
//finish the response by transmitting the file
context.Response.StatusCode = 200;
context.Response.TransmitFile(filePath);
context.Response.Flush();
context.Response.End();
}
要调用此处理程序,只需将图像的src
设置为类似于/DynamicImage.ashx?username=johndoe
的路径。
现在您的要求可能略有不同。例如,您可能正在以byte[]
的形式从数据库中检索图像,因此您可能希望使用context.Response.TransmitFile()
方法,而不是使用context.Response.BinaryWrite()
方法。此方法传输byte[]
作为响应流。
最后,我会向您推荐另一篇文章(我的),讨论从客户角度缓存这些图像。如果您的按钮会频繁生成,这将非常有用。 Leverage browser caching in IIS (google pagespeed issue)
答案 1 :(得分:0)
它可以像
一样简单<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/arrow-down.gif" OnClick="ImageButton1_Click" />
和代码背后:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
// do some DB processing here
ImageButton1.ImageUrl = "~/arrow-up.gif";
}
如果我明白你在问什么。
将它放在页面加载下会看起来像:
private void Page_Load()
{
if(!Page.IsPostBack)
{
// perform db processing here
ImageButton.ImageUrl = "~/arrow-up.gif";
}
}
就是所需要的。设置ImageUrl行可以放在任何需要的地方。