Question

my view is defined

    @model BloombergGUI.Models.SecurityViewAltModel

    <div class="col-md-10">
        @Html.TextArea("TestArea",Model.FieldsList)
        @Html.TextAreaFor(m => m.FieldsList, new {@class = "form-control"})
    </div>

if the controller for this strongly typed view is defined as

    public ActionResult Index()
    {
        return View();  //The first Html.TextArea says Model.FieldList is null
    }

if it's defined as the following, then both statements in the view work.

    public ActionResult Index()
    {
        return View(new SecurityViewAltModel());
    }

Why when the view is strongly typed is Model.Property indicating Model is null but when I explicitly pass a new model() then Model.Property works fine. I thought Model was just another way of accessing the strongly typed model for the view and m=> m.property was a lambda expression for the TextBoxFor extension method used on strongly typed views.

Was it helpful?

Solution

The

@model BloombergGUI.Models.SecurityViewAltModel

you define in the View is actually a strongly typed data passing mechanism from the controller.

when you do

 return View(); 

you should be getting a NULL Model. This is because no data is being passed to the View. Model is expected to be null.

when you do

return View(new SecurityViewAltModel());

a non-null Model object is sent with all fields null. MVC will render empty controls for these null data fields.

Note that in the second case, you might not get the Null reference exception because you're not dealing with a straight object.field reference, but an Expression.

m => m.FieldsList vs. Model.FieldsList

Details:

  1. When the expression is being evaluated, there can be checks which will prevent the null reference.
  2. Deep inside the MVC DLLs, when the Expression is being processed, it has logic as follows:

  3. Evaluate the Value of the Expression with Parameter as viewData.Model object.

The call is as follows:

CachedExpressionCompiler.Process<TParameter, TValue>(expression)(model);

And at that time, it goes into the FingerprintingExpressionVisitor and it can handle the null Model and returns null response for the Extension helper to not render any data.

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