0
var html = '@Html.Partial("_mypartialview")';
$("#container").html(html);

I am working in a single page application and I don't want to hide the container div element; instead I want to load the html content into my javascript object.

But I get the error:

Unterminated string constant.

I have tried various methods without any success. Any help as to why I get this error would be really appreciated.

1
  • Is that all your code? Check which line the error is thrown on, because no error is thrown for me. Commented Feb 27, 2015 at 9:39

1 Answer 1

2

Like this

var html = "@Html.Partial("_mypartialview").ToHtmlString().Replace("\n", "<br/>").Replace(" ", "")";

The ToHtmlString() method HTML encodes your html so the quotes won't confuse your JavaScript.

The two replace methods will remove new lines and whitespace so the content is all on one line.

Update

_mypartialview

 <div>
     <span data-bind="text:playerInfo.Name"> </span> 
</div> 

Code

 var html = "@Html.Partial("_mypartialview").ToString().Replace(Environment.NewLine, "").Replace(" ", "")"

This outputs the following

var html = "&lt;div&gt;&lt;spandata-bind=&quot;text:playerInfo.Name&quot;&gt;&lt;/span&gt;&lt;/div&gt;"
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. But still i get the same error. And the content is not in single line.
Strange it works fine for me. Can you give me the html for your partial view and I will try and reproduce the issue?
Nothing much really <div> Hello </div>
I am using asp.net mvc 5 and i copied ur code ditto.
OK I've made an update based on your html. I needed to remove the new lines.

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.