bwk4u bwk4u - 18 days ago 7
C# Question

Trying to access List<> properties from Html.DropDownListFor()

Probably I'm doing this the wrong way, but this is a sample of the code I'm dealing with:

ViewModel

public class TasDataView
{
public int nTas { get; set; }
public string codTas { get; set; }
public decimal nValue { get; set; }
public bool nState { get; set; }
public System.DateTime nDate { get; set; }
public IEnumerable<Segments> ListSegments { get; set; }
public IEnumerable<Tas> ListTas { get; set; }
}


Segments class

public class Segments
{
public int segmentValue { get; set; }
public string segmentCode { get; set; }
public bool nState { get; set; }
public System.DateTime nDate { get; set; }
}


So, when I call the View with my controller, I send an TasDataView object as parameter:

public ActionResult AddTas()
{
TasDataView TDV = new TasDataView();
SegmentsManager SM = new SegmentsManager();

TDV.ListSegments = SM.DataSegments();

return View(TDV);
}


And here is the problem I'm facing. I need all the values of ViewModel for this View to work. So, for example, I have:

@model Project.Models.ViewModel.TasDataView
@Html.EditorFor(model => model.nValue, new { htmlAttributes = new { @class = "form-control" } })


And that will create the box for inserting whatever I want into nValue. But what if I want to access the ListSegments properties (from Segments class) that I sent to the View, so I can make a DropDown List ?

I can't do something like:

@Html.DropDownListFor(x => x.ListSegments.segmentValue, new SelectList(Model.ListSegments));


because all the ListSegments (like segmentValue) properties "are not in" TasDataView, but in Segments class.

How can I reorganize my DataView to be manageable for what I want? Instead of a List<> I should have plain variables?

Answer

I guess you're doing it wrong. The first argument of DropDownListFor is an expression that represents the property of the model that receives the value of the item selected in the drop down list. It must be some dedicate=d property somewhere on your model. e.g. selectedSegment.

EDIT: So, if your goal is to present a list of values via model to the user in a drop down list and let the user pick a value, you'll need to:

  1. have a property on the model to store the selected item (segment), e.g. selectedSegment,
  2. properly render your segments as strings to present them.

The simplest solution is given below.

public class TasDataView
{
    public int nTas { get; set; }
    public string codTas { get; set; }
    public decimal nValue { get; set; }
    public bool nState { get; set; }
    public System.DateTime nDate { get; set; }
    public IEnumerable<Segments> ListSegments { get; set; }
    public IEnumerable<Tas> ListTas { get; set; }
    public Int32 selectedSegment;
}

@Html.DropDownListFor(x => x.selectedSegment, new SelectList(Model.ListSegments.Select(s => s.segmentCode)));

So there are no properties of the list you need to access.