C# String.Format - Invalid input string

2020-03-15 01:31发布

I have a MVC3 HtmlHelper extension like this:

public static MvcHtmlString ShowInfoBar(this HtmlHelper helper, string message, InfoMessageType messageType)
    {
        return MvcHtmlString.Create(String.Format(@"<script type=""text/javascript"">$(document).ready(function () { gtg.core.showInfoBar('{0}', '{1}'}; );</script>", message, messageType.ToString().ToLower()));
    }

The value of message is "The product "Product Name" was saved successfully."

The value of messageType is info.

It keeps saying Input string was not in the correct format.

I am stuck??

5条回答
成全新的幸福
2楼-- · 2020-03-15 02:04

In my case I used the bracket for JsonP formatting. JsonP requires a '{' too. By escaping the { like this: '{{', my problem was solved.

查看更多
虎瘦雄心在
3楼-- · 2020-03-15 02:07

You need to escape the curly braces:

{{ and }}

String.Format(@"<script type=""text/javascript"">$(document).ready(function () {{ gtg.core.showInfoBar('{0}', '{1}'}}; );</script>", 
              message, messageType.ToString().ToLower())
查看更多
姐就是有狂的资本
4楼-- · 2020-03-15 02:07

I have tried as below, and its working.

string.Format(@"ExecuteOrDelayUntilScriptLoaded(function () {{ Your function. 
查看更多
孤傲高冷的网名
5楼-- · 2020-03-15 02:09

Escape your squiggly brackets {{ }} in the format string

String.Format(@"<script type=""text/javascript"">$(document).ready(function () {{ gtg.core.showInfoBar('{0}', '{1}'); }});</script>", message, messageType.ToString().ToLower())
查看更多
看我几分像从前
6楼-- · 2020-03-15 02:16

On every brace that isn't a token you must double - so

function() {{

Etc

Also - consider XSS here - is message escaped correctly for inserting into JavaScript?

查看更多
登录 后发表回答