Search code examples
ruby-on-railsasp.net-mvcdynamicviewdata

ASP.NET MVC: Passing instance variables to the View like in Ruby


Yes, I know that in ASP.NET MVC you have to use ViewModels. But I'm tired of writing countless amounts of ViewModel classes. Besides I'd like to just pass the Validation model to the view, instead of that I have to pass the whole ViewModel, so I get ugly code like

Html.TextBoxFor(m => m.TopicModel.Title)

Instead of

Html.TextBoxFor(m => m.Title)

I really love RoR's @instance_variables where you just pass all the variables you need without creating new classes for that.

How can I do that? I think it's impossible because I tried everything, even C# 4 dynamic feature.

Any ideas?


Solution

  • You could use the ViewData dictionary:

    public ActionResult DoSomething()
    {
        ViewData["Message"] = "Hello World";
        return View();
    }
    

    Accessed as:

    <%= ViewData["Message"] %>
    

    You could also switch to using dynamic:

    <%@ Page Inherits="ViewPage<dynamic>" %>
    

    I think that should allow you to do:

    public ActionResult DoSomething()
    {
        return View(new { Message = "Hello" });
    }
    

    Accessed as:

    <%= Model.Message %>
    

    Because dynamics are resolved at runtime instead of compile time, it should allow you to throw an anonymous object at the view.