Reputation: 1320
Currently I have a view which takes an IEnumerable model which I use to display data on the view. However on the same view I also have a modal popup in which I want to add to the model rather than separating them out into different views. I tried to follow the suggestion at the bottom of this question How to access model property in Razor view of IEnumerable Type? but got an exception
The expression compiler was unable to evaluate the indexer expression '(model.Count - 1)' because it references the model parameter 'model' which is unavailable.
At the top of the view I have
@model IList<Test.Models.DashModel>
and within my modal body I have
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DashboardModel</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model[model.Count - 1].DashName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model[model.Count - 1].DashName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model[model.Count - 1].DashName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model[model.Count - 1].CreatedDate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model[model.Count - 1].CreatedDate, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model[model.Count - 1].CreatedDate, "", new { @class = "text-danger" })
</div>
</div>
</div>
}
Upvotes: 1
Views: 684
Reputation: 107237
I agree that overuse of the word Model, i.e. the @model
keyword, the Model
instance variable of the same type, and the default name model
given to the lambda parameter name of the HtmlHelper
methods is really confusing.
Unfortunately model
in this case is the parameter passed by the Html.*For
extension methods into your lambda. IMO the scaffolded views could have chosen a less conflicting parameter variable name for the lambdas, e.g. m
or x
etc.
To access the actual ViewModel
instance passed to the view (i.e. @model
defined at the top of your razor .cshtml
, viz @model IList<Test.Models.DashModel>
), what you want to do is to access Model
(note the case difference):
@Html.LabelFor(model => Model.Last().CreatedDate, ...
I would also recommend using the Linq
extension methods such as Last() / First()
etc rather than using the array indexers.
Out of interest, you can of course change the parameter name to anything you like, e.g.
@Html.LabelFor(_ => Model.Last().CreatedDate, ...
Upvotes: 4