C# String.Format - Invalid input string

社会主义新天地 提交于 2019-12-01 00:33:58

问题


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??


回答1:


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?




回答2:


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())



回答3:


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:


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




回答5:


I have tried as below, and its working.

string.Format(@"ExecuteOrDelayUntilScriptLoaded(function () {{ Your function. 


来源:https://stackoverflow.com/questions/7097199/c-sharp-string-format-invalid-input-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!