0
votes

I'm having an issue using the DropDownListFor() function with ASP.NET MVC:

Model:

public class ShoeSizeModel
{
    public List<ShoeModel> ShoeListModel { get; set; }
    public List<SizeModel> Sizes { get; set; }
    public int SelectedSizeId { get; set; }

    public IEnumerable<SelectListItem> SizesSelectList
    {
        get
        {
            return new SelectList(Sizes, "SizeId", "Size");
        }
    }

View:

    @model Models.ShoeSizeModel

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Shoe Selection</title>
    <link rel="stylesheet" href="../../Scripts/css/base.css">
    <link rel="stylesheet" href="../../Scripts/css/gallery.css">
</head>

<body>
    @Html.AntiForgeryToken()

    @using (Html.BeginForm("FilterBySize", "Shoe", FormMethod.Post))
    {
        <div class="refiners">
            @Html.DropDownListFor(
                     model => model.SelectedSizeId,
                     Model.SizesSelectList,
                     "Size",
                     new { onchange = "this.form.submit();" })
        </div>
    }
    ...

Controller:

[HttpPost]
public ActionResult FilterBySize(int sizeId)
{
    return View();
}

If I try to pass the SizeId from the SelectList to the FilterBySize method, I get a null value:

enter image description here

Interestingly, if I try to pass it as a model instead, the select list value passes just fine:

I'm probably just missing something obvious here, and it's not the end of the world if I just have to pass the model and take the value from there, but I'd rather just pass the value if I can. Please can someone explain to me what I'm doing wrong?

1
You are doing fine. This way it supposed to be. You don't send back anything extra when you pass the model. As you can see Shoe Models and Sizes lists are null. - Serge
Try to rename the parameter int? sizeId to int selectedSizeId, because you named it that way in your model. - David Liang
Ah I knew I was missing something dumb, in future I'll keep the name consistent. Thanks for the help! :) - MasterOfNone

1 Answers

0
votes

you will have to bind your dropdownlist with model and pass model to controller on post method.

    @model BindMvcDropdownList.Models.CategoryModel

<h1>Bind MVC DropDownList with Model</h1>

@Html.DropDownListFor(x => x.selected, Model.lstCategory)

visit - https://geeksarray.com/blog/how-to-bind-dropdownlist-in-asp-net-mvc-application