Question

I've seen a number of examples that use an anonymous type to pass data to a view. I seem to be missing a crucial bit of information, though. Consider the following contrived example:

public class BlogController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Title(object args)
    {
        return View(args);
    }

}

Index.aspx calls

<%= Html.Action("Title", new { Name = "Jake" }) %>

And title.ascx is simply:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<h3><%= Model.Name %>'s Blog</h3>

Navigating to the action in question causes a runtime exception:

'object' does not contain a definition for 'Name'

I realize that there are other ways to do this. I could make my view strongly-typed or push the data into the ViewData object. In this particular case, I want to be able to pass any object that has a Name property and bind to the Name. Is there something I'm missing?

Was it helpful?

Solution

The parameter args is of type object. When you are passing your route values to Html.Action, you're actually ending up with a string argument called Name which of course won't bind to the parameter args.

Change your call to:

<%= Html.Action("Title", new { args = new { Name = "Jake" } }) %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top