0

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....

3 Answers 3

2

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>" %>
Sign up to request clarification or add additional context in comments.

2 Comments

Why use ViewData when the YourObject already exists in the view as the Model?
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.
2

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 ;).

Comments

0

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) %>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.