问题
I am trying to extend the SelectListItem class to add another property called CardColor. However when I try to access the property in my controller I get
NullReferenceException: Object reference not set to an instance of an object....
return View("StringView", c.IssueSelected.CardColor);
Controller:
[HttpPost]
public async Task<ActionResult> CardCreate(UpdateCardFormOptions c)
{
return View("StringView", c.IssueSelected.CardColor);
}
View
@using (@Html.BeginForm())
{
<p><label>Issue Category*:</label> @Html.DropDownListFor(c => @Model.IssueSelected, Model.IssueList, new { @class = "form-control", @style = "width: 350px" })</p>
}
Model:
public IssueSelectListItem IssueSelected { get; set; }
public List<IssueSelectListItem> IssueList = new List<IssueSelectListItem>() {
new IssueSelectListItem() {Text="xxx", Value="yyy",CardColor="pink"},
};
public class IssueSelectListItem : SelectListItem
{
public string CardColor { get; set; }
}
回答1:
This post gave me a clue, turns out I needed to set the value CardColor in the View, I couldnt just set the object equivalent. My View needed to set CardColor based on my dropdown choice like this:
<p><label>Issue Category*:</label> @Html.DropDownListFor(c => @Model.IssueSelected.CardColor, Model.IssueList, new { @class = "form-control", @style = "width: 350px" })</p>
Not going to accept my own answer, still hoping someone has a better one, this just solved my immediate problem
来源:https://stackoverflow.com/questions/50159564/selectlistitem-not-setting-via-dropdown-after-extending-selectlist-class