为什么当我用jquery更改图像的src时,我的c#codebehind中的src没有改变?

时间:2011-08-08 01:01:58

标签: c# jquery asp.net

我有一个缩略图库。当您单击缩略图时,主图像将更改为使用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。

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

帮助!

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

是的,这是你的代码的正确结果,它不会更新,因为它使用来自服务器的渲染的html而不是jQuery更新的html,这是它的真实工作方式,对于你的调整,你只需调整你的代码C#代码,像这样:

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

答案 2 :(得分:0)

首先,在您的代码隐藏中执行此操作:

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')));

您可以使用“文件路径”而不是文件名,但我上面的示例应该为您提供一般概念。