如何在MVC中的Controller中获取DropDownList选择的值

时间:2015-01-12 11:43:01

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我有下拉列表,我已从数据库中填写。现在我需要在Controller中获取所选值进行一些操作。但没有得到这个想法。我试过的代码。

模型

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
}

控制器

 public ActionResult ShowAllMobileDetails()
    {
        MobileViewModel MV = new MobileViewModel();
        MV.MobileList = db.Usp_InsertUpdateDelete(null, "", "", null, "", 4, MergeOption.AppendOnly).ToList();
        MV.Vendor = new SelectList(db.Usp_VendorList(), "VendorId", "VendorName");
        return View(MV);
    }

    [HttpPost]
    public ActionResult ShowAllMobileDetails(MobileViewModel MV)
    {           
        string strDDLValue = ""; // Here i need the dropdownlist value

        return View(MV);
    }

视图

   <table>           
        <tr>
            <td>Mobile Manufacured</td>
            <td>@Html.DropDownList("ddlVendor", Model.Vendor, "Select Manufacurer") </td>
        </tr>         
        <tr>
            <td>

            </td>
            <td>
                <input id="Submit1" type="submit" value="search" />
            </td>
        </tr>
    </table>

9 个答案:

答案 0 :(得分:78)

第一种方法(通过Request或FormCollection):

您可以使用RequestRequest.Form阅读,您的下拉名称为ddlVendor,因此请在formCollection中传递ddlVendor键,以获取按表单发布的值:

string strDDLValue = Request.Form["ddlVendor"].ToString();

或使用FormCollection

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{           
  string strDDLValue = form["ddlVendor"].ToString();

  return View(MV);
}

第二种方法(通过型号):

如果需要使用模型绑定,请在模型中添加属性:

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public string SelectedVendor {get;set;}
}

并在视图中:

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")

并在行动中:

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV)
{           
   string SelectedValue = MV.SelectedVendor;
   return View(MV);
}

UPDATE:

如果您还要发布所选项目的文本,则必须添加隐藏字段,并在隐藏字段中的下拉选择更改集选定项目文本中添加:

public class MobileViewModel 
{          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public string SelectVendor {get;set;}
    public string SelectedvendorText { get; set; }
}

使用jquery设置隐藏字段:

<script type="text/javascript">
$(function(){
$("#SelectedVendor").on("change", function {
   $("#SelectedvendorText").val($(this).text());
 });
});
</script>

@Html.DropDownListFor(m=>m.SelectedVendor , Model.Vendor, "Select Manufacurer")
@Html.HiddenFor(m=>m.SelectedvendorText)

答案 1 :(得分:9)

模型

非常基本的性别字段模型。 GetGenderSelectItems()返回填充DropDownList所需的选项。

public enum Gender 
{
    Male, Female
}

public class MyModel
{
    public Gender Gender { get; set; }

    public static IEnumerable<SelectListItem> GetGenderSelectItems()
    {
        yield return new SelectListItem { Text = "Male", Value = "Male" };
        yield return new SelectListItem { Text = "Female", Value = "Female" };
    }
}

视图

请确保将@Html.DropDownListFor包裹在表单标记中。

@model MyModel

@using (Html.BeginForm("MyController", "MyAction", FormMethod.Post)
{
   @Html.DropDownListFor(m => m.Gender, MyModel.GetGenderSelectItems())
   <input type="submit" value="Send" />
}

控制器

您的.cshtml Razor视图名称应与控制器操作名称相同,文件夹名称应与控制器名称匹配,例如Views\MyController\MyAction.cshtml

public class MyController : Controller 
{
    public ActionResult MyAction()
    {
        // shows your form when you load the page
        return View();
    }

    [HttpPost]
    public ActionResult MyAction(MyModel model)
    {
        // the value is received in the controller.
        var selectedGender = model.Gender;
        return View(model);
    }
}

更进一步

现在让我们强类型和枚举独立:

var genderSelectItems = Enum.GetValues(typeof(Gender))
    .Cast<string>()
    .Select(genderString => new SelectListItem 
    {
        Text = genderString,
        Value = genderString,
    }).AsEnumerable();

答案 2 :(得分:3)

MVC 5/6 /剃刀页面

我认为最好的方法是使用强类型模型,因为Viewbags已经被大量使用了:)

MVC 5 示例

您的执行操作

public async Task<ActionResult> Register()
    {
        var model = new RegistrationViewModel
        {
            Roles = GetRoles()
        };

        return View(model);
    }

您的视图模型

    public class RegistrationViewModel
    {
        public string Name { get; set; }

        public int? RoleId { get; set; }

        public List<SelectListItem> Roles { get; set; }
    }    

您的视图

    <div class="form-group">
        @Html.LabelFor(model => model.RoleId, htmlAttributes: new { @class = "col-form-label" })
        <div class="col-form-txt">
            @Html.DropDownListFor(model => model.RoleId, Model.Roles, "--Select Role--", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.RoleId, "", new { @class = "text-danger" })
        </div>
    </div>                                   

您的帖子操作

    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegistrationViewModel model)
    {
        if (ModelState.IsValid)
        {
            var _roleId = model.RoleId, 

MVC 6会有所不同

采取行动

public async Task<ActionResult> Register()
    {
        var _roles = new List<SelectListItem>();
        _roles.Add(new SelectListItem
        {
           Text = "Select",
           Value = ""
        });
        foreach (var role in GetRoles())
        {
          _roles.Add(new SelectListItem
          {
            Text = z.Name,
            Value = z.Id
          });
        }

        var model = new RegistrationViewModel
        {
            Roles = _roles
        };

        return View(model);
    }

您的视图模型将与MVC 5相同

您的视图将类似于

<select asp-for="RoleId" asp-items="Model.Roles"></select>

帖子也将相同

剃刀页面

您的页面模型

[BindProperty]
public int User User { get; set; } = 1;

public List<SelectListItem> Roles { get; set; }

public void OnGet()
{
    Roles = new List<SelectListItem> {
        new SelectListItem { Value = "1", Text = "X" },
        new SelectListItem { Value = "2", Text = "Y" },
        new SelectListItem { Value = "3", Text = "Z" },
   };
}

<select asp-for="User" asp-items="Model.Roles">
    <option value="">Select Role</option>
</select>

我希望它可以帮助某人:)

答案 3 :(得分:1)

使用SelectList绑定@HtmlDropdownListFor并在其中指定selectedValue参数。

http://msdn.microsoft.com/en-us/library/dd492553(v=vs.108).aspx

示例:你可以这样做以获得venderid

@Html.DropDownListFor(m => m.VendorId,Model.Vendor)


   public class MobileViewModel 
   {          
    public List<tbInsertMobile> MobileList;
    public SelectList Vendor { get; set; }
    public int VenderID{get;set;}
   }
   [HttpPost]
   public ActionResult Action(MobileViewModel model)
   {
            var Id = model.VenderID;

答案 4 :(得分:1)

如果您正在寻找轻量级的东西,我会在您的操作中添加一个参数。

[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV, string ddlVendor)
{           
    string strDDLValue = ddlVendor; // Of course, this becomes silly.

    return View(MV);
}

现在你的代码中发生了什么,是你将“ddlVendor”的第一个字符串参数传递给Html.DropDownList,并告诉MVC框架创建一个<select>元素{{1} “ddlVendor”。当用户提交表单客户端时,它将包含该键的值。

当MVC尝试将该请求解析为name时,它会查找MVMobileList而找不到,因此不会填充。通过添加此参数,或者使用Vendor作为另一个答案建议,您要求MVC专门查找具有该名称的表单元素,因此它应该使用发布的值填充参数值。

答案 5 :(得分:1)

我在asp.net razor C#中遇到了同样的问题

我有一个ComboBox填充了EventMessage的标题,我希望显示此邮件的内容及其选定的值,以便在标签或TextField或任何标签中显示其他Control ...

我的ComboBox就像这样填充:

 @Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })

在我的EventController中,我有一个功能要转到页面,我想在其中显示我的ComboBox(具有不同的模型类型,所以我不得不使用局部视图) ?

从索引到页面的函数,用于加载局部视图:

  public ActionResult EventDetail(int id)
        {

            Event eventOrg = db.Event.Include(s => s.Files).SingleOrDefault(s => s.EventID == id);
            //  EventOrg eventOrg = db.EventOrgs.Find(id);
            if (eventOrg == null)
            {

                return HttpNotFound();
            }
            ViewBag.EventBerichten = GetEventBerichtenLijst(id);
            ViewBag.eventOrg = eventOrg;
            return View(eventOrg);
        }

部分视图的功能如下:

 public PartialViewResult InhoudByIdPartial(int id)
        {
            return PartialView(
                db.EventBericht.Where(r => r.EventID == id).ToList());

        }

填充EventBerichten的功能:

        public List<EventBerichten> GetEventBerichtenLijst(int id)
        {
            var eventLijst = db.EventBericht.ToList();
            var berLijst = new List<EventBerichten>();
            foreach (var ber in eventLijst)
            {
                if (ber.EventID == id )
                {
                    berLijst.Add(ber);
                }
            }
            return berLijst;
        }

partialView模型如下所示:

@model  IEnumerable<STUVF_back_end.Models.EventBerichten>

<table>
    <tr>
        <th>
            EventID
        </th>
        <th>
            Titel
        </th>
        <th>
            Inhoud
        </th>
        <th>
            BerichtDatum
        </th>
        <th>
            BerichtTijd
        </th>

    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EventID)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Titel)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Inhoud)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BerichtDatum)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.BerichtTijd)
            </td>

        </tr>
    }
</table>

VIEUW :这是用于在视图中获取输出的脚本

<script type="text/javascript">
    $(document).ready(function () {
        $("#EventBerichten").change(function () {
            $("#log").ajaxError(function (event, jqxhr, settings, exception) {
                alert(exception);
            });

            var BerichtSelected = $("select option:selected").first().text();
            $.get('@Url.Action("InhoudByIdPartial")',
                { EventBerichtID: BerichtSelected }, function (data) {
                    $("#target").html(data);
                });
        });
    });
            </script>
@{
                    Html.RenderAction("InhoudByIdPartial", Model.EventID);
                } 

<fieldset>
                <legend>Berichten over dit Evenement</legend>
                <div>
                    @Html.DropDownList("EventBerichten", new SelectList(ViewBag.EventBerichten, "EventBerichtenID", "Titel"), new { @class = "form-control", onchange = "$(this.form).submit();" })
                </div>

                <br />
                <div id="target">

                </div>
                <div id="log">

                </div>
            </fieldset>

答案 6 :(得分:0)

谢谢 - 这帮助我更好地理解了解决我遇到的问题。 为获取selectedItem的文本而提供的JQuery并没有为我工作 我把它改成了

$(function () {
  $("#SelectedVender").on("change", function () {
   $("#SelectedvendorText").val($(**"#SelectedVender option:selected"**).text());
  });
});

答案 7 :(得分:0)

如果您想使用@Html.DropDownList,请按照。

控制器:

var categoryList = context.Categories.Select(c => c.CategoryName).ToList();

ViewBag.CategoryList = categoryList;

查看:

@Html.DropDownList("Category", new SelectList(ViewBag.CategoryList), "Choose Category", new { @class = "form-control" })

$("#Category").on("change", function () {
 var q = $("#Category").val();

console.log("val = " + q);
});

答案 8 :(得分:0)

简单的解决方案不能确定是否建议这样做。对于某些事情,这可能也不起作用。话虽如此,这是下面的简单解决方案。

new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true}

List<SelectListItem> InvoiceStatusDD = new List<SelectListItem>();
InvoiceStatusDD.Add(new SelectListItem { Value = "0", Text = "All Invoices" });
InvoiceStatusDD.Add(new SelectListItem { Value = "1", Text = "Waiting Invoices", Selected = true});
InvoiceStatusDD.Add(new SelectListItem { Value = "7", Text = "Client Approved Invoices" });

@Html.DropDownList("InvoiceStatus", InvoiceStatusDD)

您还可以对数据库驱动的选择列表执行类似的操作。您将需要在控制器中设置为选中状态

@Html.DropDownList("ApprovalProfile", (IEnumerable<SelectListItem>)ViewData["ApprovalProfiles"], "All Employees")

类似的事情,但是存在更好的解决方案,这只是一种方法。

foreach (CountryModel item in CountryModel.GetCountryList())
    {
        if (item.CountryPhoneCode.Trim() != "974")
        {
            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });

        }
        else {


            countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });

        }
    }