RPM1984
RPM1984

Reputation: 73112

Trouble setting javascript object in Razor View

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?

Upvotes: 1

Views: 865

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038790

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>

Upvotes: 3

Related Questions