如何在 MVC 的 Controller 中获取 DropDownList SelectedValue

How to get DropDownList SelectedValue in Controller in MVC

我有下拉列表,我从数据库中填充了它。现在我需要在 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>

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

您可以使用 Request.FormRequest 读取它,您的下拉列表名称是 ddlVendor 因此在 formCollection 中传递 ddlVendor 键以获取其值 post按表格编辑:

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);
}

更新:

如果您还想 post 所选项目的文本,您必须添加一个隐藏字段并在下拉选择更改隐藏字段中设置所选项目文本:

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)

使用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;

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

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

    return View(MV);
}

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

当 MVC 尝试将该请求解析为 MV 时,它将查找 MobileListVendor,但两者均未找到,因此不会对其进行填充。通过添加此参数,或使用 FormCollection 作为另一个答案的建议,您要求 MVC 专门查找具有该名称的表单元素,因此它应该使用发布的值填充参数值。

型号

带有性别字段的非常基本的模型。 GetGenderSelectItems() returns select 项需要填充 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();

我在 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;
        }

部分视图模型如下所示:

@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>

谢谢 - 这帮助我更好地理解并解决了我遇到的问题。 为获取 selectedItem 的文本而提供的 JQuery 对我不起作用 我改成了

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

如果你想使用@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);
});

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>                                   

您的 Post 操作

    [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

相同

您的 View 会像

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

Post也一样

剃刀页面

您的页面模型

[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>

希望对大家有所帮助:)

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

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)

您也可以对数据库驱动的 select 列表执行类似的操作。您需要在控制器中设置 selected

@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 });

        }
    }