2

I'm new in .net platform and I'm curious about how can I pass js function with curly brackets as string inside StringBuilder.AppendFormat() c#.here is what I'm willing to do

StringBuilder sb = new StringBuilder();

sb.AppendFormat(@"<script>
       var vm = new Vue({
        el: 'main_div',
        data() { 
            return {
                proddetails: [],
            }
        },
        created: function () {
            this.proddetails = { jsonobjectplaceholder };
        },
    });
</script>");

sorry for stupidity if any and thanks in advance for the attention!

expecting a reasonable answer

Karan
  • 12,059
  • 3
  • 24
  • 40
Ram Khatri
  • 23
  • 2
  • 1
    What are you trying to do, and what does your question mean? Why are you calling `AppendFormat` a method which considers `{` and `}` as special characters. You aren't using any of the features that `AppendFormat` gives you. And why are you using a StringBuilder when all you are doing is adding a literal string to the SB – Flydog57 Jul 11 '23 at 05:01

2 Answers2

1

You are using AppendFormat where first parameter is Formatted string. And if you wish to use curly braces inside it then you need to escape them double braces {{ and }}. Try like below.

Referene : Escape curly brace '{' in String.Format

sb.AppendFormat(@"<script>
       var vm = new Vue({{
        el: 'main_div',
        data() {{ 
            return {{
                proddetails: [],
            }}
        }},
        created: function () {{
            this.proddetails = {{ jsonobjectplaceholder }};
        }},
    }});
</script>", "");

Alternatively you can use Append instead of AppendFormat. Try like below and it will work.

StringBuilder sb = new StringBuilder();

sb.Append(@"<script>
       var vm = new Vue({
        el: 'main_div',
        data() { 
            return {
                proddetails: [],
            }
        },
        created: function () {
            this.proddetails = { jsonobjectplaceholder };
        },
    });
</script>");
Karan
  • 12,059
  • 3
  • 24
  • 40
  • 1
    thanks your answer was valuable.I actually was trying to place my js code inside the format string that stringbuilder accepts as first arguement but appending it at last solved my problem. – Ram Khatri Jul 12 '23 at 08:39
0

Your code contains 'AppendFormat', did you mean to use 'Append'?

'StringBuilder.AppendFormat' is used for creating a string that is formatted with an array of strings.

For instance:

sb.AppendFormat("{0}, {1}, {2}", "var1", "var2", "var3");

The above will result in: "var1, var2, var3"

See more about StringBuilder.AppendFormat here: See Here

You can use the '@' symbol as a verbatim identifier which will allow you to include multiple lines in your string.

See Here

string exampleString = $@"This
is a
string";

So the code you want looks like the following:

StringBuilder sb = new StringBuilder();
sb.Append(@"<script> var s = 'myStringValue'; </script>");
Zaid
  • 51
  • 1
  • 3