Passing variables to javascript in onclientclick

2019-01-26 21:13发布

问题:

Okay, i think i've tried 3-4 methods here from stackoverflow, but none seems to work.

I've got:

OnClientClick='<%# Eval("albumName", "doConfirm(\"delete\", \"{0}\");").ToString() %>'

but in html it renders as:

onclick="doConfirm(&quot;delete&quot;, &quot;Test&quot;);"

Also tried making a method to call:

public string CreateConfirmation(String action, String item) {
    return String.Format(@"return confirm('Sikker på du vil {0}: {1}');", action, item);
}

With this:

OnClientClick='<%# CreateConfirmation("delete", (string)Eval(albumName)) %>'

But gives me exact same problem.... So im pretty lost?

回答1:

I apologize in advance for such a long answer, but I wanted to be thorough.

This is apparently a "security" feature in .Net 4.0 (and higher). You can read more about it at:

  • http://avinashsing.sunkur.com/2010/10/29/asp-net-html-encoding-attributes-in-server-controls/
  • http://forums.asp.net/p/1554455/3818604.aspx
  • Stop the tag builder escaping single quotes ASP.NET MVC 2

All of the above links also recommend declaring a public class to override the behavior:

public class HtmlAttributeNoEncoding : System.Web.Util.HttpEncoder
{
    protected override void HtmlAttributeEncode(string value, System.IO.TextWriter output)
    {
        output.Write(value);
    }
}

and then adding this to the <system.web> element in your web.config:

<httpRuntime encoderType="HtmlAttributeNoEncoding"/>

This definitely fixes the rendering problem, so that quotes and apostrophes render as " and ' (as expected).

That said, I tested your problem with the following:

<script type="text/javascript">
    var doConfirm = function (action, item) {
        alert('Sikker på du vil ' + action + ': ' + item);
        return false;
    };
</script>

<p>Some "arbitrary" text. <asp:Button ID="Button3" runat="server" Text="Button" OnClientClick="doConfirm('delete', 'myalbum');" /></p>
<asp:GridView ID="GridView1" runat="server">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick='<%# Eval("albumName", "doConfirm(\"delete\", \"{0}\");").ToString() %>' />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Album Name" DataField="albumName" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="Button2" runat="server" Text="Button" OnClientClick='<%# CreateConfirmation("delete", (string)Eval("albumName")) %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

and in the code-behind:

public partial class _Default : System.Web.UI.Page
{
    public string CreateConfirmation(String action, String item)
    {
        return String.Format(@"return doConfirm('{0}', '{1}');", action, item);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        DataColumn dc = new DataColumn("albumName", typeof(string));
        DataRow dr = null;

        dt.Columns.Add(dc);

        dr = dt.NewRow();
        dr["albumName"] = "Zen Arcade";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["albumName"] = "New Day Rising";
        dt.Rows.Add(dr);

        dr = dt.NewRow();
        dr["albumName"] = "Candy Apple Grey";
        dt.Rows.Add(dr);

        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

}

I was able to duplicate your rendering problem:

<p>Some "arbitrary" text.
    <input type="submit" onclick="doConfirm(&#39;delete&#39;, &#39;myalbum&#39;);" value="Button" name="ctl00$MainContent$Button3" id="MainContent_Button3" />
</p>
<div>
    <table cellspacing="0" rules="all" border="1" id="MainContent_GridView1"
    style="border-collapse:collapse;">
        <tr>
            <th scope="col">&nbsp;</th>
            <th scope="col">Album Name</th>
            <th scope="col">&nbsp;</th>
            <th scope="col">albumName</th>
        </tr>
        <tr>
            <td>
                <input type="submit" onclick="doConfirm(&quot;delete&quot;, &quot;Zen Arcade&quot;);" value="Button" name="ctl00$MainContent$GridView1$ctl02$Button1" id="MainContent_GridView1_Button1_0" />
            </td>
            <td>Zen Arcade</td>
            <td>
                <input type="submit" onclick="return doConfirm(&#39;delete&#39;, &#39;Zen Arcade&#39;);" value="Button" name="ctl00$MainContent$GridView1$ctl02$Button2" id="MainContent_GridView1_Button2_0" />
            </td>
            <td>Zen Arcade</td>
        </tr>
        <tr>
            <td>
                <input type="submit" onclick="doConfirm(&quot;delete&quot;, &quot;New Day Rising&quot;);" value="Button" name="ctl00$MainContent$GridView1$ctl03$Button1" id="MainContent_GridView1_Button1_1" />
            </td>
            <td>New Day Rising</td>
            <td>
                <input type="submit" onclick="return doConfirm(&#39;delete&#39;, &#39;New Day Rising&#39;);" value="Button" name="ctl00$MainContent$GridView1$ctl03$Button2" id="MainContent_GridView1_Button2_1" />
            </td>
            <td>New Day Rising</td>
        </tr>
        <tr>
            <td>
                <input type="submit" onclick="doConfirm(&quot;delete&quot;, &quot;Candy Apple Grey&quot;);" value="Button" name="ctl00$MainContent$GridView1$ctl04$Button1" id="MainContent_GridView1_Button1_2" />
            </td>
            <td>Candy Apple Grey</td>
            <td>
                <input type="submit" onclick="return doConfirm(&#39;delete&#39;, &#39;Candy Apple Grey&#39;);" value="Button" name="ctl00$MainContent$GridView1$ctl04$Button2" id="MainContent_GridView1_Button2_2" />
            </td>
            <td>Candy Apple Grey</td>
        </tr>
    </table>
</div>

When any of the buttons were clicked, the JavaScript function ignored the HTML encoding, alerting me to:

Sikker på du vil delete: Zen Arcade

so while it looks funky in the source, having quotes and apostrophes render as &quot; and &#39; doesn't really appear to affect anything.



回答2:

Try the following:

<asp:Button OnClientClick="Delete(this);" Text='<%# Eval("albumName"); %>' />

JS:

function Delete(element) {
    var value = element.value;
    return confirm('Delete' + value + '?');
}


回答3:

Just attach the event server side inside rowDataBound event like, (you can replace linkbutton with Button)

LinkButton myLinkButton=(LinkButton)e.row.FindControl("yourButtonName");
if(myLinkButton!=null)
{
     myLinkButton.Attributes.Add("onclick","javascript:return confirm ('Are you sure you want to delete "+ DataBinder.Eval(e.row.DataItem, "YourDbField") + " ?');");
}


回答4:

Even though this question is 5 years old, I wanted to follow up as I had the same issue with an ImageButton and was able to resolve it using a HiddenField.

Background: I have a Web User Control which I wanted to have a help button displayed if there was help available.

I added a HiddenField and an ImageButton to the User Control. I then created a property on the control so the developer may add help text.

ASPX Page

<asp:HiddenField ID="hidHelpText" runat="server" />
<asp:ImageButton ID="imgHelp" runat="server" ImageUrl="~/images/help.png" Visible="False" />

Code Behind (CS File)

public string HelpText
{
    get { return hidHelpText.Value; }
    set { hidHelpText.Value = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    imgHelp.Visible = !string.IsNullOrEmpty(HelpText);
    imgHelp.OnClientClick = string.Format("MsgBox({0}.value, MessageButtons.OK); return false;", hidHelpText.ClientID);
}

This gets around the issue as the text belongs to the hidden field instead of trying to include it within the JavaScript for the OnClientClick property.

BTW: I cannot copy and paste so this code may contain some typos but I believe it is correct. At least it points the way so you may be able to work around the issue.