views:

37

answers:

2

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?

+3  A: 

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.

Matthew Abbott
Yeah, I tried that too. But you can't use methods like Html.TextBoxFor with dynamic models.
Alex
A: 

If you don't like using view models you may pass domain models themselves. Why not?

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

Html.TextBoxFor(m => m.Title)
Alexander Prokofyev
But when I need some extra objects to pass, I have to create new ViewModel class. This system is so clumsy in ASP.NET.
Alex
It's not clumsy, its suggested, it allows you to cleanly seperate your view models, from your domain models and presentation. A goal which many developers aspire to...What is your objection to using view models? You can cut out a lot of code by using something like Automapper to map between your view model and domain model.
Matthew Abbott