I have a list of Deviation items getting from database. The list contains Severity which may be null. Thats why I made the SeverityNotNull property to transform null values to -1. BTW Severity can be 0-3.
I would like to show Deviations items in which each Severity should be a DropdownList line by line. And of course in the DropdownList the appropriate item should be selected.
my ViewModel is:
[MetadataType(typeof(DeviationMetaData))]
public partial class Deviation {
public int SeverityNotNull {
get { return Severity == null ? -1 : Severity.Value; }
}
...
}
public class DeviationMetaData {
public Nullable<int> Severity { get; set; }
...
}
public class DeviationViewModel {
public Deviation Dev { set; get; }
public IEnumerable<Deviation> Deviations {
get {
DeviationRepository dm = new DeviationRepository();
return dm.GetAll;
}
}
public DeviationViewModel() {
WindowsIdentity current = WindowsIdentity.GetCurrent();
string name = current.Name.Split(new[] { '\\' })[1];
Dev = new Deviation { CreatedBy = name, CreatedDate = DateTime.Now };
}
}
my Controller is:
public ActionResult Index() {
IList<SelectListItem> items = new List<SelectListItem> {
new SelectListItem{Text = "", Value = "-1"},
new SelectListItem{Text = "Minor", Value = "1"},
new SelectListItem{Text = "Major", Value = "2"},
new SelectListItem{Text = "Critical", Value = "3"}
};
ViewBag.SelectSeverity = new SelectList(items, "Value", "Text");
return View( new DeviationViewModel() );
}
my View is:
@model DeviationViewModel
@using (Html.BeginForm()) {
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.Dev.Severity)
</th>
</tr>
@foreach (var item in Model.Deviations) {
<tr>
<td>
@Html.DropDownListFor(modelItem => item.SeverityNotNull, (SelectList)ViewBag.SelectSeverity)
</td>
</tr>
}
</table>
</fieldset>
}
</div>
I checked the SeverityNotNull values and they are correct. In the result there are the Dropdownlists, but nothing is selected. That is the problem. Could you give me some idea? Thanks.
Severitycan be null, what is the point ofSeverityNotNull? Why do you need totransform null values to -1? Your going about this all wrong and it wont even bind on postback anyway