skip to Main Content

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

2

Answers


  1. 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>");
    
    Login or Signup to reply.
  2. 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>");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search