Escape apostrophe when passing parameter in onclick event

后端 未结 3 983
执笔经年
执笔经年 2020-12-20 15:05

I\'m passing the company name to an onclick event. Some company names have apostrophes in them. I added \'.Replace(\"\'\", \"'\")\' to the company_name field. This al

3条回答
  •  孤城傲影
    2020-12-20 15:36

    There are two options as I see it.

    1. If you wrap the parameters in quotes (") instead of apostrophes/single quotes (') then you shouldn't need to escape it at all. HTML encoding will take care of encoding any quotes (if they are in the string) and the apostrophe's won't be a problem. Though, as the javascript is already wrapped in quotes, you will need to backslash escape your quotes. eg:

      onclick="return Actionclick(\"<%= Url.Action("Activate", new {id = item.company_id}) %>\", \"<%= Html.Encode(item.company1.company_name) %>\");"

    2. Backslash escape the company name as it's only the final javascript string that needs the apostrophe escaped, not the HTML. eg:

      onclick="return Actionclick('<%= Url.Action("Activate", new {id = item.company_id}) %>', '<%= Html.Encode(item.company1.company_name.Replace("'", "\\'")) %>');"

提交回复
热议问题