0

During Edit I am getting the values form table ScannerTypes as follows into ViewBag as follows

ViewBag.ScannerTypeID = new SelectList(db.ScannerTypes, "ScannerTypeID", "Name", db.ScannerTypes);

For few rows the value of ScannerTypeID could be null. If the ScannerTypeID is null, I want to show default message as "Select Scanner Type" else I want to show the selected Name. Here is my Razor code

<div class="form-group">
    @Html.LabelFor(model => model.ScannerTypeID, "Scanner Type", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("ScannerTypeID", null, "Select Scanner Type", htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ScannerTypeID, "", new { @class = "text-danger" })
    </div>
</div>

Unfortunately for all edit I am getting messages as "Select Scanner Type".

abatishchev
  • 98,240
  • 88
  • 296
  • 433
bp581
  • 859
  • 1
  • 16
  • 47
  • You need to set the value of property `ScannerTypeID` in the GET method before you pass the model to the view. And delete the `db.ScannerTypes` property from the `SelectList` constructor (the `Selected` property is ignored when binding to a property). –  Feb 28 '17 at 21:33
  • And you cannot have the same name for the property and the `SelectList` (refer [this answer](http://stackoverflow.com/questions/37161202/will-there-be-any-conflict-if-i-specify-the-viewbag-name-to-be-equal-to-the-mode/37162557#37162557)) - use `ViewBag.ScannerList = ....` and `@Html.DropDownListFor(m => m.ScannerTypeID", (SelectList)ViewBag.ScannerList, .... )` –  Feb 28 '17 at 21:33
  • But you have said _For few rows_ - are you doing something in a loop? (in which case you need other changes as well) –  Feb 28 '17 at 21:34

0 Answers0