Louise
Louise

Reputation: 77

Trying to get the selection of a dropdown list

I'm trying to get the selection from the drop-down list and save it into the database as its corresponding primary key.

When the user makes a selection, I am unable to use that selection. I think I am not collecting the correct information in my controller.

Here is my view:

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

Here is my controller

public ActionResult Create(CreateCommunicationViewModel commmodel){
...

   var typeIDquery = db.Types.Where(g => g.TypeName == commmodel.Type.TypeName).Select(g => g.TypeID);
   typeID = typeIDquery.AsEnumerable().FirstOrDefault().Trim().ToString();

Upvotes: 0

Views: 95

Answers (1)

Chih-Ho Andy Chou
Chih-Ho Andy Chou

Reputation: 63

I am not sure if you posted your complete code of your view but I think you are missing the HTML form:

@using (Html.BeginForm("Create", "YourControllerName", FormMethod.Get)) {....}

And in your Create method your parameter name has to match the name of dropdown list you are trying to catch:

public ActionResult Create(string Types){....}

The 'Types' parameter at your action method should be the selected value from the dropdown list.

Upvotes: 1

Related Questions