How does MVC framework assign model to a view while returning it from Controller?

1k views Asked by At

This is a bit confusing. Till today i knew the following ways to pass data to view in MVC ViewBag,ViewData,TempData,Strongly Typed Views and its Models. So wherever we used a strongly typed view, we used to pass a model with data or empty object to a view, so that it does not throw any null reference error.

But today encountered a behavior that made me feel strange.

Case-1

The following is the EmployeeController's Create action

    //
    // GET: /Employee/Create

    public ActionResult Create()
    {
        return View("Create");
    }

The following is the CreateView inside Employee Folder or Views.

@model EmployeeDataBase.Models.Employee




<fieldset>
    <legend>Employee</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

I am not returning any model in the action,but still the view was rendered.

Case-2

My action

    public ActionResult Create(Employee employee, Employee emp)
    {
        return View("Create");
    }

Called the above using the following URL

http://localhost:50128/Employee/Create?Name=something

Both the Employee parameters in the action were instantiated with Name property value as "something". Did not return anything in the action, still create is rendered. If if a dynamically change the value of Name during debugging, its still shows "something" in Create view in the Name text box.

1

There are 1 answers

0
CodingYoshi On

Case 1:

If you had passed a model into the view, it would have displayed that model. If you do not pass a model, the view simply uses your model class to create the controls. In this case it is creating labels, textboxes and validation for all the properties. It uses those lambda expressions in LabelFor (xxxFor) as Expression Trees and analyses your class. It analyses and looks for things like: In the model you may have used a Display("Full Name") attribute for Name property, therefore it will conclude you want to show "Full Name" in label instead of "Name". It creates validation javascript in the same manner.

Therefore, in order to use the expression tree given in lambdas, it does not need an instance of the model.

Case 2:

Has been addressed in this SO question.