确定 ViewData 的结果计数

发布于 2024-07-10 01:07:04 字数 404 浏览 4 评论 0原文

您好,我有一个包含多个用户控件的视图,我将 ViewData 传递给所有这些控件,我想知道如何通过指定字符串键来确定元​​素计数。 我知道您不能使用与整数的比较,因为 ViewData 是一个对象,但我以这种方式设置它来解释我的问题。 我也尝试过 null,但 ViewData 对象永远不会为 null,即使对于 ViewData 中没有填充数据的结果也是如此。 即

在我看来

    <%if(ViewData["Test"].Values > 0)
      {
    %>
      <%=Html.RenderPartial("~/Views/UC/Test.ascx", ViewData["Test"])%>
   <%
      }
    %>

Hi I have a view with several User Controls and I pass ViewData to all of them, I would like to know how you would determine the element count by specifying the string key.
I understand that you cannot use comparison to an integer because ViewData is an object but I have it setup this way for explaining my question. I have also tried null but The ViewData object is never null, even for results where no data is populated in the ViewData. I.e

In my View

    <%if(ViewData["Test"].Values > 0)
      {
    %>
      <%=Html.RenderPartial("~/Views/UC/Test.ascx", ViewData["Test"])%>
   <%
      }
    %>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北方。的韩爷 2024-07-17 01:07:04

如果我正确理解你的问题,你想从存储在 ViewData 中的元素中获取计数。
实现此目的的唯一方法是将其强制转换为 IEnumerable 或 IList,然后调用 Count 方法。

If I understood your question correctly, you want to get the count out of an element stored inside the ViewData.
The only way to achieve this is by casting it to IEnumerable or IList and then call the Count method.

完美的未来在梦里 2024-07-17 01:07:04

为了回答我自己的问题,这是我这样做的路径。 在我的控制器操作方法中,我根据在那里检索到的记录数确定计数,如果不满足我的要求,则将 ViewData 设置为 null。

public ActionResult Test(){
   var test = //your query;
   if(test.Count() > 0 )
   {
       ViewData["Test"] = test;
   }
}

现在,如果没有检索到任何内容,它会自动将 ViewData["Test"] 设置为 null,并且在您的视图页面中您可以执行类似的操作。

<% if(ViewData["Test"] == null){
      Html.RenderPartial("~/Views/UC/NoRecords.ascx");
   }
   else
   {
      Html.RenderPartial("~/Views/UC/Awesome.ascx");
   }
%>

如果您想添加多个检查,则必须将它们添加到控制器中并使用视图页面进行比较。 可能还有其他方法可以做到这一点,但我发现这种方法效果很好。

To answer my own question this is the path I took about doing this. In my controller action method I determine the count based on number of records retrieved there and set my ViewData to null if it doesn't meet my requirements.

public ActionResult Test(){
   var test = //your query;
   if(test.Count() > 0 )
   {
       ViewData["Test"] = test;
   }
}

Now if nothing is retrieved it automatically sets the ViewData["Test"] to null and in your view Page you could do something like this.

<% if(ViewData["Test"] == null){
      Html.RenderPartial("~/Views/UC/NoRecords.ascx");
   }
   else
   {
      Html.RenderPartial("~/Views/UC/Awesome.ascx");
   }
%>

If you wanted to add multiple checks you must add them in your controller and compare using your view page. There are probably other ways of doing this but I found this works well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文