1

I'm trying to set a JavaScript object in my main view:

<script type="text/javascript">
   xx.yy.zz = 
   {
     a: @Model.Id,
     b: '@Model.Name',
     c: @Html.Raw(Model.JsonFeature)
   }
</script>

Property "a" is an int.

Property "b" is a string.

Property "c" is also a string on the server side, but it's actually a JSON-encoded string, hence my use of @Html.Raw.

But the problem is that field could be empty, so i'm trying to do something like this:

<script type="text/javascript">
   xx.yy.zz = 
   {
     a: @Model.Id,
     b: '@Model.Name',
     c: @(Model.JsonFeature != null ? Html.Raw(Model.MappingViewModel.JsonFeature) : null)
   }
</script>

And it's causing all sorts of problem, e.g renders this:

<script type="text/javascript">
   xx.yy.zz = 
   {
     a: 1,
     b: 'Foo',
     c: 
   }
</script>

And so it cracks it with "Unexpected token }" (understandable).

How do i set a javascript property to a string value, or empty, using a Razor C# conditional?

1
  • Would you even like to have c if it is null? I mean you want all your data to have { a: 1, b:'Foo', c: "" } or just a and b if c is null? Commented May 7, 2012 at 7:26

1 Answer 1

3

Try like this:

<script type="text/javascript">
    xx.yy.zz = @Html.Raw(Json.Encode(new {
        a = Model.Id,
        b = Model.Name,
        c = Model.JsonFeature != null && !string.IsNullOrEmpty(Model.MappingViewModel.JsonFeature)
            ? Json.Decode(Model.MappingViewModel.JsonFeature)
            : (string)null
    }));
</script>
Sign up to request clarification or add additional context in comments.

Comments

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.