C# 在Razor视图中设置javascript对象时出现问题

C# 在Razor视图中设置javascript对象时出现问题,c#,javascript,asp.net-mvc-3,razor,C#,Javascript,Asp.net Mvc 3,Razor,我正在尝试在主视图中设置JavaScript对象: <script type="text/javascript"> xx.yy.zz = { a: @Model.Id, b: '@Model.Name', c: @Html.Raw(Model.JsonFeature) } </script> xx.yy.zz= { a:@Model.Id, b:“@Model.Name”, c:@Html.Raw(Model.Json

我正在尝试在主视图中设置JavaScript对象:

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

xx.yy.zz=
{
a:@Model.Id,
b:“@Model.Name”,
c:@Html.Raw(Model.JsonFeature)
}
属性“a”是一个int

属性“b”是一个字符串

属性“c”在服务器端也是一个字符串,但它实际上是一个JSON编码的字符串,因此我使用@Html.Raw

但问题是字段可能是空的,所以我尝试这样做:

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

xx.yy.zz=
{
a:@Model.Id,
b:“@Model.Name”,
c:@(Model.JsonFeature!=null?Html.Raw(Model.MappingViewModel.JsonFeature):null)
}
它引起了各种各样的问题,例如:

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

xx.yy.zz=
{
答:1,,
b:‘福’,
c:
}
因此它用“意外标记}”(可以理解)来破解它

如何使用Razor C#conditional将javascript属性设置为字符串值或空?

尝试如下:

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

xx.yy.zz=@Html.Raw(Json.Encode)(新{
a=模型Id,
b=型号。名称,
c=Model.JsonFeature!=null&&!string.IsNullOrEmpty(Model.MappingViewModel.JsonFeature)
?Json.Decode(Model.MappingViewModel.JsonFeature)
:(字符串)null
}));

如果c为空,您是否希望使用它?我的意思是,您希望所有数据都有{a:1,b:'Foo',c:'}或者如果c为null,则只有a和b?