MVC 4 - 如何从下拉列表中获得所选项目 [英] MVC 4 - How to get the selected item from a dropdown list

查看:146
本文介绍了MVC 4 - 如何从下拉列表中获得所选项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的MVC使用。我有以下剃刀code:

I am very new with MVC. I have the following Razor code:

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset style="margin:5px">
        <legend>List a Bicycle for Sale</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.BicycleManfacturer)
        </div>
        <div class="editor-field">
            @Html.DropDownList("ManufacturerList")
        </div>

        ....
        ....


        <div class="float-right">
            <input type="submit" value="List Bike" />
        </div>
    </fieldset>
}

ManufacturerList是 SelectedListItem 存储在ViewBag列表(我不想为我所有下拉列表创建模型)。它可以通过这种方法建立:

"ManufacturerList" is a List of SelectedListItem stored in the ViewBag (I didn't want to create models for all my dropdown lists). It's build via this method:

    private void HydrateManufacturerList()
    {
        var manufacturerList = (from row in db.BicycleManufacturer.ToList()
                                select new SelectListItem
                                {
                                    Text = row.Description,
                                    Value = row.BicycleManufacturerId.ToString()
                                }).ToList();
        manufacturerList.Add(new SelectListItem
        {
            Text = "-- Select Manufacturer --",
            Value = "0",
            Selected = true
        });
        ViewBag.ManufacturerList = manufacturerList.OrderBy(row => row.Text);
    }

我有以下的code时,提交完成被调用:

I have the following code that gets called when a Submit is done:

    [HttpPost]
    public ActionResult Create(BicycleSellerListing bicyclesellerlisting)
    {
        bicyclesellerlisting.ListingDate = System.DateTimeOffset.Now;

        if (ModelState.IsValid)
        {
            db.BicycleSellerListing.Add(bicyclesellerlisting);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(bicyclesellerlisting);
    }

我想不通用户帖子的观点回我的控制器,并且此方法在执行时如何从下拉列表中选择制造商。

What I can't figure how to get the selected manufacturer from the dropdown list when the user posts the view back to my controller and this method is executed.

推荐答案

使用

public ActionResult Create(BicycleSellerListing bicyclesellerlisting, FormCollection collection)
{ 
  ...

您可以得到所有的输入,包括选取下拉例如集[ManufacturerList] 或类似取决于您的下拉列表名称。

You can get all the inputs including the drop down selected items like collection["ManufacturerList"] or similar depending on your drop down list name.

这篇关于MVC 4 - 如何从下拉列表中获得所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆