强类型的MVC形式映射为不同的类型? [英] Strongly typed form in MVC which maps to a different type?

查看:151
本文介绍了强类型的MVC形式映射为不同的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我与@ Html.TextBoxFor方法指定表单输入,那么生成的输入元素不一定会映射到在窗体的操作方法期望的类型。

When I specify form inputs with the @Html.TextBoxFor method, then the generated input element would not necessarily map to the type that is expected in the form's action method.

让我们说我有两个类:

public class HomeA
{
    public int A { get; set; }
}

public class HomeB
{
    public int B { get; set; }
}

HomeA是我的看法的模式。如果一个控制器动作预计HomeB,那么我可以不是我的形式提供一个强类型的方式所需的输入元素:

HomeA is the model of my view. If a controller action expects HomeB, then I can't provide the necessary input element in a strongly typed manner in my form:

@using (Html.BeginForm())
{
    @Html.TextBoxFor(model => model.A)
}

此形式显然不会映射到HomeB的属性。

This form will obviously not map to HomeB's property.

推荐答案

控制器动作不应该期望HomeB。
使用每个动作一个视图模式。
如果要发送XYZ的视图模型,然后在你的一般需要ActionMethod XYZ的视图模型。
这就是我的总体思路反正一致性/可读性。
但是,如果你的作品,这样做只要关系是存在的。

The controller action should not expect HomeB. Use one view model per action. If you are sending a ViewModel of XYZ, then in general your ActionMethod takes a ViewModel of XYZ. Thats my general thoughts anyways for consistency/readability. However if it works for you, do it as long as the relation is there.

<一个href=\"http://stackoverflow.com/questions/7407596/asp-net-mvc-one-viewmodel-per-view-or-per-action\">ASP.net MVC - 按次或每个动作一视图模型

至于对作文的说明与继承退房
<一href=\"http://stackoverflow.com/questions/6954102/asp-net-mvc-architecture-viewmodel-by-composition-inheritance-or-duplication\">ASP.NET MVC架构:通过组合,继承或复制视图模型

As for the note on composition vs. inheritance check out ASP.NET MVC Architecture : ViewModel by composition, inheritance or duplication?

查看
http://lostechies.com/jimmybogard/2009/04/ 24 /如何-WE-DO-MV​​C /

这篇关于强类型的MVC形式映射为不同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆