SelectListItem not setting via dropdown after extending SelectList class

旧城冷巷雨未停 提交于 2020-01-03 06:08:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!