Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I always initialize view model object?

Tags:

c#

asp.net-mvc

I'm reading a book about ASP.NET MVC 4 and I've got a little question. Here is the view model

public class SignupViewModel
{
    public string Username { get; set; }
    public string Password { get; set; }
    public string Password2 { get; set; }
    public string Email { get; set; }
}

The book's author suggests to create object of this type to call a view from the controller.

    public ActionResult Index()
    {
        if (!Security.IsAuthneticated)
        {
            return View("SignupPge", new SignupViewModel());
        }

    }

The view itself is strongly typed

    @model SignupViewModel
    <p>
        @using (var signupForm = Html.BeginForm("Signup", "Account"))
        {
            @Html.TextBoxFor(m => m.Email, new { placeholder = "Email" })
            @Html.TextBoxFor(m => m.Username, new { placeholder = "Username" })
            @Html.PasswordFor(m => m.Password, new { placeholder = "Password" })
            @Html.PasswordFor(m => m.Password2, new { placeholder = "Confirm Password" })

            <input type="submit" value="Create Account" />
        }
    </p>
}

I just wonder was this really necessary to create object of the view model when calling the view? In fact, I tried to pass null as model object and everything worked perfectly. I guess the MVC Framework has created the model object itself. If this is ok, then is it considered as a good practice?

like image 787
Alexei Pancratov Avatar asked Nov 10 '22 15:11

Alexei Pancratov


1 Answers

From defensive coding perspectives, when you implement a function that accepts parameters, your function should not assume that the parameters are always valid (null is an example of something invalid).

In my opinion, Asp.net mvc follows these best practices and tries to avoid exception when you pass null as a view model.

I just wonder was this really necessary to create object of the view model when calling the view?

I think it's necessary when you have your custom logic to initialize the object and you need to pass that object to the view. In my opinion, we should always pass in the object we need, that's clearer in the code and avoid relying on the defensive logic in the method. The defensive logic in the method is to defend the method from invalid parameters and sometimes won't work as you expected.

like image 72
Khanh TO Avatar answered Nov 14 '22 22:11

Khanh TO