Question

Obviously real life applications are a lot more complex but for this example sake lets say I have the following simple view and I need to save the User:

@model UserViewModel


@Html.TextBoxFor(model=>model.FirstName)
</br>
@Html.TextBoxFor(model=>model.MiddleName)
</br>
@Html.TextBoxFor(model=>model.LastName)

When submitted there are two ways how I can receive it at the Controller level:

1)

public ActionResult(UserViewModel user)
{
 var myUser = new User();
 myUser = user.FirstName;
 myUser = user.MiddleName;
 myUser = user.LastName;
}

and

2)

public ActionResult(FormCollection collection)
{
 var myUser = new User();
 myUser = collection.Get("FirstName");
 myUser = collection.Get("MiddleName");
 myUser = collection.Get("LastName");
}

Question: Is there a reason to use one method over another ? Also a few developers told me that second method is preferred. That passing object the whole object like shown in the first example is not a good idea. Why ?

Was it helpful?

Solution

Short answer: both are working and both are valid.

Long opinionated answer: I do prefer the first one,

  1. its more object oriented than the second one.
  2. you implicitly have magic strings in second approach. Of course you can externalize them etc, but again, strong types are always better than going string by string.
  3. you define your validations once in option 1, you have to do it over and over again in option 2.
  4. you can use AutoMapper. It will map most of fields with similar names for you and ask you to define the rest. Here you don't have to move field by field at all (see below). You must however do it one by one in the second approach. It will look like this when you done with mappings (which is also trivial to do):

    public ActionResult(UserViewModel user)
    {
       var myUser = Mapper.Map<User, UserViewModel>(user);
    }
    

Isn't it a beauty?

I don't really see any reason why would option 2 be preferred over 1... I guess they have their reasons. Its like COBOL vs. C++. :))

But this is really individual decision and style. There's no right answer.

Hope this is of help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top