简体   繁体   English

为什么url参数在javascript中格式不正确?

[英]Why url parameter doesn't have correct format in javascript?

I have to create a javascript which contains an url in code behind page using C#. 我必须创建一个JavaScript,其中使用C#在页面后面的代码中包含一个url。 But the url parameter inside javascript doesn't have correct format after generated by C#. 但是,JavaScript内部的url参数由C#生成后,格式不正确。

Example: 例:

Url parameter: http://google.com 网址参数: http //google.com

Javascript: javascript:dnnModal.show(' http://google.com ',false,365,206,false) Javascript: javascript:dnnModal.show(' http ://google.com',false,365,206,false)

C# code: C#代码:

string link = "http://google.com?popUp=true";
string googleIcon = "<a href='javascript:dnnModal.show('" + link +',false,365,206,false)'><img border='0' src='~/Icons/gIcon.png'></a>";

After generated from code behind the page view the url incorrect format. 从页面后面的代码生成后,URL格式不正确。 There is the code of googleIcon after I am using "View Select Source" to view the code of aspx page: 我使用“查看选择源代码”查看aspx页面的代码后,有googleIcon的代码:

<a href="javascript:dnnModal.show(" http:="" google.com?popup="true',false,365,206,false)'"><img src="~/Icons/gIcon.png" border="0"></a>

The hyperlink on icon just show this when I move the mouse over it: 当我将鼠标移到图标上时,图标上的超链接将显示此内容:

javascript:dnnModal.show(

The url is lost and the remind string is lost too. 网址丢失,提醒字符串也丢失。

I need some help on my issue to show the way how to pass an url parameter into javascript using C#. 我需要一些有关我的问题的帮助,以展示如何使用C#将url参数传递到javascript中的方法。

应该是这样的

string googleIcon = "<a href=\"javascript:dnnModal.show('" + link + "',false,365,206,false)'\"><img border='0' src='~/Icons/gIcon.png'></a>";

您没有正确地转义字符串

string googleIcon = "<a href='javascript:dnnModal.show(\"" + link +"\",false,365,206,false)'><img border='0' src='~/Icons/gIcon.png'></a>";

I agree with two other answers, but you should try to encapsulate these kind of tasks in a user control maybe. 我同意其他两个答案,但是您应该尝试将此类任务封装在用户控件中。 but if that's not possible I suggest to use System.Web.UI.HtmlControls instead, since it will give you more flexibility. 但是,如果那不可能,我建议改用System.Web.UI.HtmlControls ,因为它将为您提供更大的灵活性。
Something like this: 像这样:

            HtmlLink myHtmlLink = new HtmlLink();
            myHtmlLink.Href = @"javascript:dnnModal.show(\"" + link +"\",false,365,206,false)";
            HtmlImage myImage = new HtmlImage();
            myImage.Src = "~/Icons/gIcon.png";
            myImage.Border = 0;
            myHtmlLink.Controls.Add(myImage);  

I like this approach more because Asp.net is responsible for creating DOM, which means that you will be safe and you're guaranteed to get a valid XHTML result. 我更喜欢这种方法,因为Asp.net负责创建DOM,这意味着您将很安全,并且可以保证获得有效的XHTML结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM