In my view I'm returning some results from a webservice and storing them in a session variable.
Here's the Session Storage Method:
//AreaSummary[] is a reference to the webservice reference gubbins
public AreaSummary[] Results
{
get
{
if (this.Results != null)
{
return this.Results;
}
else
{
if (HttpContext.Current.Session["Results"] != null)
{
this.Results =
(AreaSummary[])HttpContext.Current.Session["Results"];
return this.Results;
}
else
{
return null;
}
}
}
set
{
this.Results= null;
HttpContext.Current.Session["Results"] = value;
}
}
In the Controller I set the results to this session to save having to push the request again and again (for paging).
So I set the session to the result set:
this.mySess.SessionVarss.Results = myservice.SearchForX("stuff");
Both the 'Results
' and 'SearchForX
' are of AreaSummary[]
ViewData["ResultSet"] = this.mySess.SessionVars.Results;
I then pass this as ViewData
in the controller without an issue and databind
it to a repeater
or datagrid
(that i get).
My first thought was to use a foreach
loop.
So in the view I was trying:
<% foreach (var item in (ViewData["ResultSet"] as List<MyMVC.webservice.AreaSummary[]>))
{ %>
<li class="image">
<img src="<%=item.MainImage.ImageUrl %>" />
</li>
<% } %>
I'm sure the mistake is glaringly obvious to some and I'm missing it through the tunnel-vision.
It compiles fine, but dies with the following error:
Object reference not set to an instance of an object.
The following works:
<%
placelist.DataSource = ViewData["ResultSet"];
placelist.DataBind();
%>
<asp:Repeater ID="productlist" runat="server" Visible="true">
<ItemTemplate>
<li class="image">
<img src="<%# DataBinder.Eval(Container.DataItem, "MainImage.ImageUrl")%>" />
</li>
</ItemTemplate>
</asp:Repeater>
But I'd prefer to use a foreach
loop as some of the items returned are arrays and with the repeater
I'll end up doing more.
Proper Solution
The better solution in the end was to pass the data to the view:
return View("index",SearchResults);
Then right click -> add view
, index
, create strongly typed view
, select webservice.AreaSummary
and list
.