Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String.Format - Invalid input string

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

like image 737
Sam Avatar asked Aug 17 '11 17:08

Sam


4 Answers

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?

like image 182
Marc Gravell Avatar answered Sep 21 '22 10:09

Marc Gravell


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())
like image 25
Louis Ricci Avatar answered Sep 20 '22 10:09

Louis Ricci


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())
like image 44
Mrchief Avatar answered Sep 19 '22 10:09

Mrchief


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

like image 40
Noldy Avatar answered Sep 18 '22 10:09

Noldy