Search code examples
asp.net-mvcwebgridhtml.dropdownlistfor

Can I use DropDownListFor in a WebGrid?


My problem seems to be the Html.DropDownLisTFor helper uses the page model, not the current row item. Is there a way around this?

This is my viewmodel:

 public class DropTest
    {
        public IEnumerable<DropQuestion> DropQuestions { get; set; }
    }
    public class DropQuestion
    {
        public Int32? QuestionNo { get; set; }
        public Int32? Status { get; set; }
        public IEnumerable<SelectListItem> IStatuses { get; set; }
    }

and this is the view I want:

@model Blah.ViewModels.DropTest   
@{

    var DGrid = new WebGrid(Model.DropQuestions);
}

@DGrid.GetHtml(
columns: DGrid.Columns(

    DGrid.Column("QuestionNo", "Question No"),
//I need this to work picking up the correct status for the current row??
    DGrid.Column("Status", "StatusFor",
        format: @<text>
        @Html.DropDownListFor(x => x.Status, Model.IStatuses)
   `     </text>),
         )))

I can use DropDownList but this doesn't correctly assign "Selected"

Thanks in advance for any advice.

My problem was fixed by adding a temporary type to the model and assigining it the Status value in another column. This could be improved by doing all the work in one column by I couldn't figure out how without getting errors?? My ViewmModel has now had this amendment:

public class DropTest
{
    public IEnumerable<DropQuestion> DropQuestions { get; set; }
    public Int32 GridStatus { get; set; }
}

and the view:

DGrid.Column("QuestionNo", "Question No",
         format: ((item) => { Model.GridStatus = item.Status ?? 0; return item.QuestionNo; } )),
DGrid.Column("Status", "StatusFor",
        format: @<text>
        @Html.DropDownListFor(x => x.GridStatus, Model.IStatuses)
        </text>),

Hope this helps someone or could even be improved to perfection by someone else!


Solution

  • Basically I added a new temporary variable to the model called GridStatus and use that instead of Status. Within any column in the grid it has to be assigned to item.Status