views:

308

answers:

2

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"])%>
   <%
      }
    %>
+3  A: 

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.

CodeClimber
A: 

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.

Ayo