Pergunta

I am creating x numbers of dropdownlist on the view and want to bind the selected value back to the view model on post. I have seen Scott's post and tried to write my code but still can't get it to work.

My view model consists of two items. One is for the name label for dropdownlist and one is for selected value. I need the selected value because I need to pre-select the dropdownlist.

VM

public class ColumnMapperVm
{
    public string Column { get; set; }
    public string SelectedValue { get; set; }
}

The view take a list of view model. The reason is because i don't know the number of dropdownlist that i need to have on the design time. It varies to users.

@model List<ColumnMapperVm>

@for (int i = 0; i < Model.Count; i++ )
{
    <tr>
        <td style="width: 50%;">
            @Html.DisplayFor(m => m[i].Column)               
        </td>
        <td>
            @Html.DropDownList("SelectedValue", new SelectList(ViewBag.Columns, "StaticName", "DisplayName", Model[i].SelectedValue))
        </td>
    </tr>
}

I put the selectlist in a viewbag coz i want to keep my view model clern and i don't select list won't get posted back to the server.

And here is my controller

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult MapColumns(List<ColumnMapperVm> colmapper)
    {
          //colmapper is null
    }

Of course, I got the values in FormCollection but model binder isn't binding the view model and I wonder how to make it work.

Foi útil?

Solução

One probable cause might be the fact that currently all dropdowns on post add values with the same name to the request. To work this around you can use DropDownListFor:

@Html.DropDownListFor(m => m[i].SelectedValue, new SelectList(ViewBag.Columns, "StaticName", "DisplayName"))

This should ensure all dropdowns have correct name in HTML markup.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top