这是使用 ASP.NET Web Forms .NET 2.0 -
我遇到的情况是不确定如何满足所有要求。如果从同一页面上的下拉列表中进行选择,我需要更新页面上的 img 源。
基本上,下拉菜单是该项目的“选项”。如果做出选择(即颜色:红色),那么我会将产品的 img 更新为类似 (productID_red.jpeg) 的内容(如果存在)。
问题是我不想在每次做出选择时都进行回发并刷新页面 - 特别是如果我在换出该产品的 img src 之前检查图像是否存在文件不存在,所以我只是刷新了整个页面。
问题:
所以我很容易地将一些 JavaScript 放在一起,根据所选的选项制定图像文件名的字符串。我的问题是,我必须采取哪些选择才能执行以下操作:
将构造的图像名称(即productID_red_large.jpg)提交到某个位置,以验证该文件是否存在于 C# 中,或者是否可能存在于 javascript 中。我还必须检查不同的可能文件类型(即 .png、.jpg...等)。
不回发并刷新整个页面
有什么建议吗?
最佳答案
submit the constructed image name (i.e. productID_red_large.jpg) to some where that will verify the file exists either in C# or if it is even possible in the javascript. I also have to check for different possible file types (i.e. .png, .jpg...etc.).
not do a post back and refresh the entire page
如果您不想发回该页面,您需要查看 $.ajax()或$.post() (这只是 $.ajax()
的简写,带有一些默认选项)
要处理该请求,您可以使用 Generic Http Handler .
一个简单的大纲可以如下所示:
帖子的 jQuery 示例:
$("someButton").click(function () {
//Get the image name
var imageToCheck = $("#imgFileName").val();
//construct the data to send to the handler
var dataToSend = {
fileName: imageToCheck
};
$.post("/somePath/ValidateImage.ashx", dataToSend, function (data) {
if (data === "valid") {
//Do something
} else {
//Handle error
}
}, "html");
})
然后在您的 asp.net 端,您将创建一个 http 处理程序来验证该请求。
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var fileName = context.Request["fileName"];
var fullPath = Path.Combine("SomeLocalPath", fileName);
//Do something to validate the file
if (File.Exists(fullPath))
{
context.Response.Write("valid");
}
else
{
context.Response.Write("invalid");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
希望这会有所帮助,如果我在这方面完全没有达到要求,请告诉我,我可以修改。
关于c# - 关于如何更新 DOM 但使用隐藏代码检查数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5091211/