Just starting out using MVC3 and hit a problem trying to build a drop-down in a view. The ViewModel is populated with a SelectList of items:
mdm.CaptionSetList=new SelectList(CaptionSet.Fetch(), "CaptionSetId", "Description")
which then is used in the view:
@Html.DropDownListFor(model => model.Entity.CaptionSetId, model.CaptionSetList)
but when the page is hit, the line is highlighted with the compiler message:
Compiler Error开发者_开发知识库 Message: CS0103: The name 'model' does not exist in the current context
What's the beginner's mistake I'm making?
The first argument for DropDownListFor is a function so that part is right, but the second part is just expecting a SelectList so all you need to do is
@Html.DropDownListFor(model => model.Entity.CaptionSetId, Model.CaptionSetList)
Note the capitalization.
Further clarification
In a strongly typed view Model
is a property that refers to the model bound to the view. Since the second argument is just expecting a list and you've specified that the Model has a property called CaptionSetList, You specify the list as Model.CaptionSetList
. If you had put the list in the ViewBag
, you would put ViewBag.CaptionSetList
.
Contrast this to the first argument which is a function that takes one argument of the same type as the model.
Got the same error.
In my case, I had done some search and replace and forgot to change the lambda expression:
@Html.DropDownListFor(m => model.StagingDelegate.ManagerId, new[]{
new SelectListItem() {Text = "ManagerId 1", Value = "1"},
new SelectListItem() {Text= "ManagerId 2", Value= "2"},
}, "Choose a Manager", new { @class = "form-control form-control-sm " })
Replace m => with model =>:
@Html.DropDownListFor(model => model.StagingDelegate.ManagerId, new[]{
new SelectListItem() {Text = "ManagerId 1", Value = "1"},
new SelectListItem() {Text= "ManagerId 2", Value= "2"},
}, "Choose a Manager", new { @class = "form-control form-control-sm " })
精彩评论