tags:

views:

87

answers:

3

Is it possible to return a complex type from a controller to a view in asp.net mvc? All the examples I have looked at so far demonstrate passing simple intrinsic types like int, string....

+2  A: 

You can pass any object type to the view using the ViewData Dictionary.

Just put in your controller:

ViewData["example"] = (YourObject)data;

And then in your view:

<%= ((YourObject)ViewData["example"]).YourProperty %>

And if you want to pass your object as your View model then:

return View("viewname", (YourObject)data);

And make sure your view looks like this:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<YourObject>" %>
Drevak
Why use ViewData when the YourObject already exists in the view as the Model?
Peter J
i was trying to say that he can either pass the object using the viewdata or directly as the view model. My answer was very poor i admit.
Drevak
A: 

Use a ViewModel for your page.

you could use a view model containing both complex and simple objects, for example:

public class MyComplexViewModel
{
    public Address UserAddress { get; set;}
    public List<string> ValidZipCodes { get; set; }
    public string Message { get; set; }
}

If your view inherits the generic ViewPage with something like this

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyComplexViewModel>" %>

you could then in the view use the view model as Model.:

<%= Html.Encode(Model.UserAddress.SomeAddressProperty) %>
<%= Html.Encode(Model.ValidZipCodes.Count) %>
<%= Html.Encode(Model.Message) %>
MatteKarla
+2  A: 

You can create a viewmodel that's then used in the strongly typed view. You can check out this blogpost by Stephen Walther that explains it. I started out just dumping stuff in viewdata, but that gets confusing pretty quickly ;).

Morph