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?

4

2 回答 2

3

您可以使用 ViewData 字典:

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

访问为:

<%= ViewData["Message"] %>

您也可以切换到使用动态:

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

我认为这应该允许你这样做:

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

访问为:

<%= Model.Message %>

因为动态是在运行时而不是编译时解析的,所以它应该允许您在视图中抛出一个匿名对象。

于 2010-08-24T06:46:27.287 回答
0

如果您不喜欢使用视图模型,您可以自己传递域模型。为什么不?

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

Html.TextBoxFor(m => m.Title)
于 2010-08-24T07:23:13.303 回答