【问题标题】:Pass dropdownlist value to controller将下拉列表值传递给控制器
【发布时间】:2018-11-26 11:12:49
【问题描述】:

我有下拉列表并想在 Controller 中传递值。查看

@using (Html.BeginForm())
{  
    @Html.DropDownList("dropOrg", ViewBag.dropOrg as SelectList)
    <input type="submit" value="save" />
}

控制器

foreach (int tmp in org)
{
   string s = tmp + " - " + orgNames[tmp];
   SelectListItem item1 = new SelectListItem() { Text = s, Value = tmp.ToString() };
   items.Add(item1);
}
ViewBag.dropOrg = items;

我该怎么办?

【问题讨论】:

标签: c# asp.net asp.net-mvc model-view-controller drop-down-menu


【解决方案1】:

如果你为你的视图创建 ViewModel 会更好:

public class SampleViewModel
{
    public string DropDownListValue { get; set; }
}

然后在控制器的 get 方法中:

public ActionResult SomeAction()
{
    var org = GetOrg(); //your org
    var orgNames = GetOrgNames(); //your orgNames

    // . . .

    ViewBag.DropDownListValue = new SelectList(org.Select(s => 
    new SampleViewModel 
    {  
        DropDownListValue = $"{s} - {orgNames[s]}"
    }, "DropDownListValue", "DropDownListValue");
    return View(new SampleViewModel())
}

您的SomeAction 查看:

@model YourAppNamespace.SampleViewModel
<h1>Hello Stranger</h1>

@using (Html.BeginForm())
{
    @Html.DropDownList("DropDownListValue")
    <input type="submit" value="Submit"/>
}

请注意:

DropDownList 帮助器用于创建 HTML 选择列表 需要IEnumerable&lt;SelectListItem&gt;,无论是明确的还是 含蓄地。也就是说,你可以通过IEnumerable&lt;SelectListItem&gt; 明确地添加到 DropDownList 助手,或者您可以添加 IEnumerable&lt;SelectListItem&gt;ViewBag 使用相同的名称 SelectListItem 作为模型属性。

我们在这里使用了隐式传递,即我们为SelectListItemViewBag 使用了相同的名称(即DropDownListValue)。

那么当你点击Submit时,你需要HttpPost方法为SomeAction

[HttpPost]
public ActionResult SomeAction(SampleViewModel model)
{
    var org = GetOrg(); //your org
    var orgNames = GetOrgNames(); //your orgNames

    //. . . Validation etc..

    ViewBag.DropDownListValue = new SelectList(org.Select(s => 
    new SampleViewModel 
    {  
        DropDownListValue = $"{s} - {orgNames[s]}"
    }, "DropDownListValue", "DropDownListValue", model.DropDownListValue);


    var doSomething = model.DropDownListValue; //Your selected value from DropDownList
    return View(model)
}

参考:DotNetFiddle Example Using the DropDownList Helper with ASP.NET MVC

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-11
    相关资源
    最近更新 更多