0

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; }
}
Rilcon42
  • 9,584
  • 18
  • 83
  • 167

1 Answers1

0

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

Rilcon42
  • 9,584
  • 18
  • 83
  • 167
  • Your `IssueSelectListItem` is a bit pointless since the `DropDownListFor()` method accepts `IEnumerable` as the 2nd parameter, and your additional `CardColor` property is just ignored. And your `IssueSelected` property makes no sense either ans will never bind correctly (you cannot bind a ` –  May 04 '18 at 08:28
  • @StephenMuecke my goal is to pass multiple parameters to a SelectList and be able to save them all, eg based on which SelectListItem they choose I would also like to retain info about the CardColor that was associated with it – Rilcon42 May 07 '18 at 17:10
  • Unless you were to create your own extension method to create a `` only posts back a simple value - the value of your selected option (which in your case will be `"xxx"`) –  May 07 '18 at 23:07