简体   繁体   English

检查部分视图是否在ASP.Net MVC中返回Null或为空

[英]Check if Partial View Returns Null or Empty in ASP.Net MVC

I have a View with a Partial View in it. 我有一个局部视图的视图。 Both the View and the Partial View have their own View Model (VM). 视图和部分视图都具有自己的视图模型(VM)。 In the Views VM I create a property of the Partial Views VM and then I pass that property into the RenderAction for the Partial view. 在Views VM中,我创建Partial Views VM的属性,然后将该属性传递到Partial视图的RenderAction中。

@{ Html.RenderAction("PartialItem", "_PViewItem", Model.PV_Page_Item); }

In some cases the Partial View will have data in it and others it will be null. 在某些情况下,部分视图中将包含数据,而在其他情况下,它将为null。 There are several other bits of HTML in the parent View that I only want to show if the Partial View has data in it. 父视图中还有其他几段HTML,我只想显示部分视图中是否包含数据。

What I need to know is how can I tell if the Partial View returns data or is Null? 我需要知道的是如何判断Partial View是否返回数据或为Null?

You can put an IF around the RenderAction. 您可以在RenderAction周围放置一个IF。 As others mentioned, it's too late if the partial is already being loaded to stop showing it. 正如其他人提到的那样,如果已经加载了部分内容以停止显示为时已晚。

Something like (the if happens on server side) 诸如此类(如果发生在服务器端)

if (Model.PV_Page_Item != null)
{
@{ Html.RenderAction("PartialItem", "_PViewItem", Model.PV_Page_Item); }
}

In your action you could do something like . 在您的操作中,您可以执行类似操作。

{
var result = Repository.GetData();

          if (result.Any())
            {
                return PartialView("_yourPartialView", result);
            }
            return null;
}

And in your client code add a null check condition and display result accordingly. 并在您的客户端代码中添加一个空检查条件并相应地显示结果。

I would not do it this way. 我不会这样做。 I would rather return the partial view irrespective if there is data in it or not. 我宁愿返回partial view无论其中是否有数据。 I am not sure what your partial view looks like, but rather do a check in the partial view on the item, if the item does not contain data then do not display the HTML in the partial view. 我不确定您的局部视图是什么样子,而是在项目的局部视图中进行检查,如果项目不包含数据,则不要在局部视图中显示HTML

Let us assume I have user data in my view coming from a view model , and a list of that user's addresses that I want to send to the partial view. 让我们假设我的视图中有来自view model用户数据,以及要发送到部分视图的该用户的地址列表。 Then I would have something like the code below. 然后我会有类似下面的代码。 UserAddresses is the name of the partial view that I want to pass data to: UserAddresses是要将数据传递到的部分视图的名称:

@Html.Partial("UserAddresses", Model.Addresses)

So in the partial view I would just do the following: 因此,在部分视图中,我将执行以下操作:

@if (Model.Count > 0)
{
     foreach (var address in Model)
     {
          <div>@address.Line1</div>
          <div>@address.Line2</div>
          <br />
     }
}

So there is no real need to check for a null partial view, just do not display any HTML if no data is passed through. 因此,实际上没有必要检查是否有空的局部视图,只是如果没有数据通过就不显示任何HTML。

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

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