Lennac
Lennac

Reputation: 186

DropDownList does not have value when item is selected to pass on form submit

This is part of a .NET MVC project.

I have a DropDownList that is populated by an array of strings from my model. The actual list functions fine and populates correctly, but when an item is selected, there is no value passed. The value should just be equal to the text being selected from the dropdownlist.

I can see that it likely isn't assigned anywhere, but I'm relatively inexperienced with MVC/HTML projects.

        <div class="form-group">
            @Html.LabelFor(model => model.Cores, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Cores", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Cores, "", new { @class = "text-danger" })
            </div>
        </div>

The code I'm using is modified from a larger project that I've (apparently) taken over, so I'm learning as I go with this.

EDIT:

This is how the list of cores is initialized and passed to the view page.

var cores = db.Cores.ToList();
            var coreName = new List<string>();

            foreach (Core core in cores)
            {
                coreName.Add(core.Name);
            }

            ViewBag.Cores = new SelectList(coreName);

            return View();

Upvotes: 1

Views: 1538

Answers (1)

Okan Kocyigit
Okan Kocyigit

Reputation: 13421

You're just creating a dropdown which is not binded to your model. You should use Html.DropDownListFor, not Html.DropDownList.

public class MyModel {
   public string Core { get; set; }
}

In your view file,

@Html.DropDownListFor(n => n.Core, (SelectList)ViewBag.Cores, htmlAttributes: new { @class = "form-control" })

And post action in your controller

[HttpPost]
public ActionResult Report(MyModel model)
{
   //model.Core is selected core.
}

UPDATE:

If you don't have a Model,

In your view file,

@Html.DropDownList("Core", (SelectList)ViewBag.Cores, htmlAttributes: new { @class = "form-control" })

And post action in your controller

[HttpPost]
public ActionResult Report(string Core)
{
   //Core is the selected one.
}

Upvotes: 2

Related Questions