0

I have a string which I add in my controller..

ViewBag.mydata = "a,x,b,\na,y,b,....."

In my view in javascript code I call..

var myvar= @ViewBag.mydata;

when I see the view source html I find

var myvar = a,x,b,
            a,y,b,
            .......

I need myvar to be the string I sent in ViewBag..

Thanks

1
  • 1
    well, \n will do that to a string :-) Commented Oct 8, 2014 at 14:14

1 Answer 1

2

Try

var myvar= '@ViewBag.mydata';

Seems you having that because with @ViewBag.mydata you outputing just contents of your C# string to make it as a javascript string you need to wrap that into quotes.

Update 1.

If you wan't to keep your \n's displaying you need to escape \ and that could be achieved by duplicating that sign:

var myvar= '@ViewBag.mydata'.replace('\n', '\\n');
Sign up to request clarification or add additional context in comments.

3 Comments

Does not help.. it adds a quote in front and end but /n gets converted to new line
@Arnab from your question it seems like that should be an answer. Can you describe better what you want you acheive? I take that you want \n displayed on UI, right? How you are using your myvar?
My 'var myvar' code was in js, so replace did not help, but thanx to your providing the '\\n', I was able to solve the problem by sending the data from controller with \\n instead of \n and that did it..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.