为什么当我用jquery改变图像的src时,src在我的c#代码后面没有改变

本文关键字:改变 src 代码 我的 jquery 图像 为什么 | 更新日期: 2023-09-27 18:04:41

我有一个缩略图库。当你点击一个缩略图时,主图像会变成使用jQuery点击的缩略图,并改变的'src'标签。这工作如预期。

$('#ContentPlaceHolder1_photoSpotImage').attr('src', src.replace(/-thumbs/, ''));

我有一个链接,当单击该链接时,使用标题中的Content-Disposition方法使图像成为可下载文件。当在代码中硬设置时,它会按预期工作。

<asp:LinkButton runat="server" PostBackUrl="" ID="link2TheDownload" Text="+ download it" onclick="link2TheDownload_Click"></asp:LinkButton>

现在,我已经在代码后面以编程方式添加了从标记的'src'标记获取所选图像的文件名。

    string thisServerName = Request.ServerVariables["SERVER_NAME"].ToString();
    string thisHref = "http://" + thisServerName + "/" +photoSpotImage.Src.ToString();
    Uri uri = new Uri(thisHref);
    string filename = Path.GetFileName(uri.LocalPath);
    string thisAttachment = "attachment; filename=" + filename.ToString();
    Response.ContentType = "image/jpeg";
    Response.AppendHeader("Content-Disposition", thisAttachment.ToString());
    Response.TransmitFile(strDirectFilePath.ToString() + "/photos/1/" + filename.ToString());
    Response.End();

c#只有最初设置为Onload的文件名,看起来jQuery并没有改变src.

我需要获得当前文件名,以便用户可以下载正确的图像文件。

帮助!

为什么当我用jquery改变图像的src时,src在我的c#代码后面没有改变

JQuery只在客户端操作DOM。它不会修改视图状态,并且图像不包含在POST请求中。您必须返回一个隐藏的表单字段与正确的值。

是的,这是你代码的正确结果,它不会更新,因为它使用的是服务器渲染的html而不是jQuery更新的html,这就是它的实际工作方式,对于你的调整你可以在c#代码中调整代码,像这样:

string thisServerName = Request.ServerVariables["SERVER_NAME"].ToString();
photoSpotImage.Src.ToString().Replace("-thumbs", string.Empty);

首先,在代码后面执行此操作:

photoSpotImage.Attributes["data-filename"] = "image.jpg";

现在,这将在客户端输出如下内容:

<a id="ContentPlaceHolder1_photoSpotImage" data-filename="image.jpg">Test hyperlink</a>

由于将文件名嵌入到a元素的属性中,因此可以使用jQuery形成文件的完整URL:

$('#ContentPlaceHolder1_photoSpotImage').attr('src', $('#ContentPlaceHolder1_photoSpotImage').attr('data-filename')));

你可以使用"file-path"来代替filename,但我上面的例子应该给你一个大致的概念。