处理部分和空模型值中的空模型
我在弄清楚如何在将模型传递给局部变量以及处理模型中的空值时处理空值时遇到问题。
在此块中:
@section TaskBar{
@Html.Partial("_TaskBar", Model);
}
我收到此错误: e:\Views\Shared_TaskBar.cshtml(107): 错误 CS1002: ;预期的
???
另外,我尝试过的部分中存在空值问题
: this.userID = ko.observable("@if(Model.UserID == null){"null"}else{Model.UserID}");
并
this.userID = ko.observable("@(Model.UserID == null)?"null" :Model.UserID");
与;等等...
所以我的问题是..我的部分经常会传递一个空模型..那么如何处理部分方法以及如果为空如何在视图中处理?谢谢!
i am having problems figuring out how to handle nulls when passing models to partials as well handling null values in models.
In this block:
@section TaskBar{
@Html.Partial("_TaskBar", Model);
}
I get this error:
e:\Views\Shared_TaskBar.cshtml(107): error CS1002: ; expected
???
also, having problem with nulls in the partial
I've tried:
this.userID = ko.observable("@if(Model.UserID == null){"null"}else{Model.UserID}");
and
this.userID = ko.observable("@(Model.UserID == null)?"null" :Model.UserID");
with ; etc...
So my question is.. my partial will often be passed a null model.. so how to handle the partial method and if null how to handle in the view? thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不清楚你的 Model null 是什么意思,因为你的示例检查 UserId 是否为 null 而不是模型本身。因此,假设您打算检查整个模型,我个人将在视图开头使用一个简单的
if
。或者当您定义
RenderSection 时传递 Required=false ,因此在声明该部分时,无论模型是否有价值,您都可以有选择地执行此操作。
在你的layout.cshtml中
在你的页面中
I don't clearly understand what you mean with Model null, because your example check if UserId is null and not the Model itself. So, assuming you mean to check the entire Model, personally I will use a simple
if
at the start of my view.Something like this
Or when you define the
RenderSection
pass theRequired=false
so when declaring the section, you can selectively do that if the model has value or not.In your layout.cshtml
In your pages
为了简化您的代码,您应该使用空对象模式。
您可以使用初始化为空/无意义值的对象,而不是使用 null 来表示不存在的值。这样,您就不需要检查几十个地方是否有 null 值,也不需要获取 NullReferenceExpections,以防万一您错过了它。
甚至还有一种更简单的方法,源自于此。无需创建特定的 NullObject 类,只需传递所需类的新实例即可。如果它是一个简单的 ViewModel,这通常就足够了,因为 C# 已经为您初始化了值,并且可能是您大多数时候想要的。
In order to simplify your code you should utilize the Null Object pattern.
Instead of using null to represent a non existing value, you use an object initialized to empty/meaningless values. This way you do not need to check in dozens of places for nulls and get NullReferenceExpections in case you miss it.
There is even a simpler approach, derived from this. Instead of creating a specific NullObject class, just pass a new instance of the class you require. If it is a simple ViewModel, this usually is enough, since C# already initializes the values for you, and is likely what you want most of the time.