Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format - what is wrong in my string?

Tags:

.net

asp.net

I using String.Format this way:

String.Format("$(function() { $('{0}').menu(); });", "blaId");

I get an exception:

An exception of type 'System.FormatException' occurred and was caught.

How can I fix this?

like image 981
Naor Avatar asked Dec 21 '25 05:12

Naor


2 Answers

You should escape { characters like this: {{, unless they are a part of placeholders like {0}.

String.Format("$(function() {{ $('{0}').menu(); }});", "blaId");
like image 133
Dmytro Shevchenko Avatar answered Dec 22 '25 19:12

Dmytro Shevchenko


You have an invalid index value inside your curly braces. String.Format recognises this as a place holder for the formatting.

{ $('{0}').menu(); }

To resolve this, use double curly braces to escape:

String.Format("$(function() {{ $('{0}').menu(); }});", "blaId");
like image 33
Curtis Avatar answered Dec 22 '25 18:12

Curtis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!