简体   繁体   English

在JavaScript中使用空C#模型

[英]Using a null c# model in javascript

i'm trying to use my viewmodel from Razor in my script. 我试图在脚本中使用Razor的ViewModel。 The problem is that sometimes, my complex Model generated by EF which have cyclic values is null. 问题在于,有时我由EF生成的具有循环值的复杂模型为null。

var skill = @Model.Skill1 != null ? "@Model.Skill1.SkillName" : "";

When the @Model.Skill1 is not null, i can use @Model.Skill1.SkillName. 当@ Model.Skill1不为null时,我可以使用@ Model.Skill1.SkillName。 But if @Model.Skill1 is null the result is 但是,如果@ Model.Skill1为null,则结果为

Object reference not set to an instance of an object.

And the page is not even render. 而且页面甚至没有呈现。

It seem that @Model.Skill1.SkillName can't be write in the code even if the condition to access the property SkillName is not triggered. 即使未触发访问属性SkillName的条件,似乎也无法在代码中写入@ Model.Skill1.SkillName。

So i tried to convert my object into a Json object but this time i have the cyclic values generating problem. 所以我试图将我的对象转换为Json对象,但是这次我遇到了循环值生成问题。

Any idea or way to bypass the problem? 有什么办法可以绕过这个问题吗?

You're mixing languages. 您正在混合语言。 If this is in your JavaScript block: 如果这在您的JavaScript块中:

var skill = @Model.Skill1 != null ? "@Model.Skill1.SkillName" : "";

then you have two server-side statements there. 那么那里有两个服务器端语句。 With no logic determining whether or not to execute them. 没有逻辑来确定是否执行它们。 So they both execute, and the second one is a NullReferenceException . 因此它们都执行,第二个是NullReferenceException

Basically, you're trying to emit a null reference to the client and so the client can check if it's null. 基本上,您尝试发出对客户端的空引用,以便客户端可以检查其是否为空。 But by then you've already tried to dereference it, hence the error. 但是到那时,您已经尝试取消引用它,因此出现了错误。

Conduct the null check server-side and just emit the result to the client-side code. 服务器端进行null检查,然后将结果发送到客户端代码。 Something like this: 像这样:

var skill = '@(Model.Skill1 != null ? Model.Skill1.SkillName : "")';

Wrapping a value-emitting expression in parentheses in Razor @() means that the whole statement is server-side code and should result in a single emitted value. 在Razor @()括号中包装一个值发射表达式,这意味着整个语句是服务器端代码,并且应该导致一个发射值。

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

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