How do I get the selected item from drop down list

2019-03-04 05:35发布

问题:

I have an mvc razor form. What i want is to submit the user's selection from Items dropdown list and navigate to Details view in order to access the chosen item's information.

Currently when i click the submit button i navigate succesfully to Details view but there is absolutely no data showing there.

Can you please help me?

View

@using (Html.BeginForm("Details", "Bookings", FormMethod.Post))
{
<fieldset>
    <legend> Type/Item</legend>
    <label for="Items">Item Types </label>
    @Html.DropDownList("department", ViewBag.ItemTypesList as SelectList, "Select a Type", new { id = "ItemTypeID" })
    <div id="ItemsDivId">
        <label for="Items">Items </label>
        <select id="ItemsID" name="Items"></select>
    </div>
    <p>
        <input type ="submit" value="Submit" id="SubmitID" />
    </p>
 </fieldset>
}


    <script type="text/javascript">

        $('#ItemTypeID').on('change', function () {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetItemTypeForm")',
            data: { itemTypeId: $('#ItemTypeID').val() },
            success: function (results) {
                var options = $('#ItemsID');
                options.empty();
                options.append($('<option />').val(null).text("- Select an Item -"));
                $.each(results, function () {
                    options.append($('<option />').val(this.ItemsID).text(this.Value));
                });
            }
        });
    });
</script>

Controller:

 public ActionResult Details(string id)
        {
            var item = db.Items.Find(id);

            return View(item);
        }

[HttpPost]
        public JsonResult GetItemTypeForm(string itemTypeId)
        {
            //pseudo code
            var data = from s in db.Items
                       where s.ItemType.ItemTypeName == itemTypeId
                       select new { Value = s.ItemName, ItemsID = s.ItemId };


            return Json(data);
        }

回答1:

use Items in Details method if you want to get Items value

  public ActionResult Details(int Items)
    {
        var item = db.Items.Find(Items);

        return View(item);
    }


回答2:

A dropdown only sends simple values. The name usually have to match the name of the parameter in the method signature. Remember that it is the name attribute that is the key in the querystring, and not the id attribute. Hence the use of department in this example and Items in @Murali's answer.

Try changing your details method to:

 public ActionResult Details(string department)
    {
        var item = db.Items.Find(department);

        return View(item);
    }