Home > Back-end >  DropDownListFor not selecting
DropDownListFor not selecting

Time:01-15

I have a DropDownListFor that doesn't seem to be setting the expected Model property. Here's the HTML:

@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.SelectedItem, 
        new SelectList(Model.ItemList, "Id", "Desc"), null, 
        new { @class = "selected-list", @size = "3" });  

    <div>
        @Model.SelectedItem
    </div>
    <input type="submit" value="Do Stuff" 
            asp-controller="My" 
            asp-action="DoStuff"
            asp-route-itemId="@Model.SelectedItem" />  
    </div>      
}

The div is just there for debugging purposes, and it either shows 0 or blank. The underlying model has a property:

public int SelectedItem { get; set; }

I've also tried a string:

public string SelectedItem { get; set; } = String.Empty;

(Hence why 0 or blank)

The actual list itself displays fine, it just doesn't update the model on select. How can I get it to update the model?

CodePudding user response:

If you use asp-route-itemId, your action need contains parameter named itemId to receive the value. But for your scenario, it seems to be useless to receive such value, because it will always receive the value you set instead of the dropdown changed value.

Here is a simple demo you could follow and check if any difference with yours:

Model

public class TestVM
{
    public string SelectedItem { get; set; } = String.Empty;
    public List<Item> ItemList { get; set; } 
}
public class Item
{
    public int Id { get; set; }
    public string Desc { get; set; }
}

View(Index.cshtml)

@model TestVM
@using (Html.BeginForm())
{
    @Html.DropDownListFor(x => x.SelectedItem, 
        new SelectList(Model.ItemList, "Id", "Desc"), null, 
        new { @class = "selected-list", @size = "3" });  

    <div>
        @Model.SelectedItem
    </div>
    <input type="submit" value="Do Stuff" 
            asp-controller="Home" 
            asp-action="DoStuff" />  
}

Controller

[HttpGet]
public IActionResult Index()
{
    //Note: hard-coded the model just for easy testing.....
    var model = new TestVM()
    {
        SelectedItem = "1",
        ItemList = new List<Item>()
        {
            new Item(){Id=1,Desc="aa"},
            new Item(){Id=2,Desc="bb"},
            new Item(){Id=3,Desc="cc"}
        }
    };
   
    return View(model);
}
[HttpPost]
public IActionResult DoStuff(TestVM model)
{
    return View("index", model);
}

Result

enter image description here

  • Related