Determining the number of ViewData results

Hi I have a view with several user controls and I am passing the ViewData to all of them, I would like to know how you define an item count by specifying a string key. I understand that you cannot use integer comparison because ViewData is an object, but I have a setting to explain my question. I also tried null, but the ViewData object is never null, even for results when no data is populated in the ViewData. I.e

In my mind

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

      

0


source to share


2 answers


If I understand your question correctly, you want to get the counter from the item stored inside the ViewData. The only way to achieve this is to cast it to an IEnumerable or IList and then call the Count method.



+4


source


To answer my own question, this is the path I took to do this. In my controller action method, I determine the score based on the number of records found 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 received, it automatically sets ViewData ["Test"] to null, and in your view page you can do something like this.



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

      

If you want to add multiple checks, you must add them to your controller and compare using your view page. There may be other ways to do this, but I found it works well.

0


source







All Articles