简体   繁体   English

无法在Razor View中设置javascript对象

[英]Trouble setting javascript object in Razor View

I'm trying to set a JavaScript object in my main view: 我正在尝试在主视图中设置JavaScript对象:

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

Property "a" is an int. 属性“a”是一个int。

Property "b" is a string. 属性“b”是一个字符串。

Property "c" is also a string on the server side, but it's actually a JSON-encoded string, hence my use of @Html.Raw. 属性“c”也是服务器端的字符串,但它实际上是一个JSON编码的字符串,因此我使用了@ 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, eg 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? 如何使用Razor C#条件将javascript属性设置为字符串值或为空?

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM