1

I have an ASP.NET MVC app. One of the views in my app has some JavaScript. I want to set the value of a JavaScript variable based on a value in the ViewBag. If the ViewBag value exists and is not null, I want to use it. Otherwise, I want to assign an empty string value to the JavaScript variable. Here's what I'm currently trying:

<script type='text/javascript'>
  function formatItem(item) {
    var itemName = @(ViewBag.ItemName ? ViewBag.ItemName : '');
    alert(itemName);
  }
</script>

This block throws an error that says:

Compiler Error Message: CS1011: Empty character literal

Is there a way to do what I'm trying to do? If so, how?

Thanks!

1
  • Tip: Don't forget that Razor will escape all strings. If you want to prevent that and you're 100% sure there's noting evil in that string you can use @Html.Raw() Commented Sep 30, 2014 at 15:14

2 Answers 2

3

You just need to use an empty string instead of a character literal (double quotes versus single quotes):

<script type='text/javascript'>
function formatItem(item) {
    var itemName = '@((!string.IsNullOrEmpty(ViewBag.ItemName)) ? ViewBag.ItemName : "")';
    alert(itemName);
}
</script>

Your only real problem was that you used '' instead of "". '' Means a character, "" means a string;

Sign up to request clarification or add additional context in comments.

Comments

3

You need double quotes and not single quotes.

var itemName = '@(String.IsNullOrEmpty(ViewBag.ItemName) ? ViewBag.ItemName : "")';

even better you might want to use the String object:

var itemName = '@(String.IsNullOrEmpty(ViewBag.ItemName) ? ViewBag.ItemName : String.Empty)';

1 Comment

This is not JavaScript. ViewBag.ItemName is not boolean. He needs to use something like ?? or string.IsNullOrEmpty

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.