Strongly typed form in MVC which maps to a differe

2019-08-28 02:06发布

问题:

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.

Let's say I have two classes:

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

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

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)
}

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

回答1:

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.

ASP.net MVC - One ViewModel per View or per Action?

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

Check out http://lostechies.com/jimmybogard/2009/04/24/how-we-do-mvc/



回答2:

You would create a HomeAB class that contains both a HomeA and HomeB



回答3:

If you have to create and to show some items which belong to both classes A & B, you can design an interface and then inherit that interface. Or you can create another class AB which inherits from A & B.

Hope this helps!