0

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.

Attila Kun
  • 2,215
  • 2
  • 23
  • 33
  • If `HomeA` and `HomeB` are identical except for their names, why do you need two classes to begin with? Metadata? – Cᴏʀʏ Nov 11 '11 at 17:46
  • Cory: HomeA may be used to display various information, while HomeB only contains data which is necessary to save something in a datastore. – Attila Kun Nov 11 '11 at 17:48
  • Ok, so like a Model vs. a DTO. Are you aware that you can instruct a controller to ignore certain fields when binding to a model on an action method? – Cᴏʀʏ Nov 11 '11 at 18:07
  • @Cory: Maybe I misunderstand you, but I can't see how that would solve my problem. – Attila Kun Nov 11 '11 at 18:11

3 Answers3

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/

Community
  • 1
  • 1
Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
0

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

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
0

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!

RG-3
  • 6,088
  • 19
  • 69
  • 125