如何在 MVC 的控制器中获取 DropDownList SelectedValue
Posted
技术标签:
【中文标题】如何在 MVC 的控制器中获取 DropDownList SelectedValue【英文标题】:How to get DropDownList SelectedValue in Controller in MVC 【发布时间】:2015-03-10 04:06:40 【问题描述】:我有从数据库中填写的下拉列表。现在我需要在 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>
【问题讨论】:
您已将下拉列表绑定到属性ddlVendor
,但您的模型中不存在此类属性。添加属性int SelectedVendor
或类似于您的模型并绑定到它。
【参考方案1】:
第一种方法(通过 Request 或 FormCollection):
您可以使用 Request.Form
从 Request
读取它,您的下拉名称是 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);
更新:
如果您还想发布所选项目的文本,您必须添加一个隐藏字段,并在下拉选择更改时在隐藏字段中设置所选项目文本:
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)
【讨论】:
@Raghubar 第二种方法更受欢迎,所以使用模型绑定 好的。并请告诉我如何在下拉列表中设置所选项目。 @Raghubar,只需在控制器中设置属性SelectVender
的值以匹配其中一个选项的值
这种方式在post action中:MV.Vendor = new SelectList(db.Usp_VendorList(), "VendorId", "VendorName",VM.SelectedVendor);
最后一个参数用来设置选中的值
@EhsanSajjad 如何获取选中的文本?【参考方案2】:
型号
带有性别字段的非常基本的模型。 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();
【讨论】:
'IEnumerableMVC 5/6/Razor 页面
我认为最好的方法是使用强类型模型,因为 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>
我希望它可以帮助某人:)
【讨论】:
【参考方案4】:如果你想使用@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);
);
【讨论】:
【参考方案5】:如果您正在寻找轻量级的东西,我会在您的操作中附加一个参数。
[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
为“ddlVendor. "当用户在客户端提交表单时,它将包含该键的值。
当 MVC 尝试将该请求解析为 MV
时,它会查找 MobileList
和 Vendor
并且两者都找不到,因此不会填充。通过添加此参数,或使用 FormCollection
作为另一个答案的建议,您要求 MVC 专门查找具有该名称的表单元素,因此它应该使用发布的值填充参数值。
【讨论】:
【参考方案6】:使用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 VenderIDget;set;
[HttpPost]
public ActionResult Action(MobileViewModel model)
var Id = model.VenderID;
【讨论】:
@Raghubar - 它不适合你......或任何人......我只是想知道原因,以便我可以改进...... @PranayRana,取消了它——但必须承认,在您编辑之前,我正准备将其标记为 仅链接答案 - 也许反对者也有同样的感觉【参考方案7】:我在 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>
【讨论】:
【参考方案8】:谢谢 - 这帮助我更好地理解并解决了我遇到的问题。 为获取 selectedItem 的文本而提供的 JQuery 不适合我 我把它改成
$(function ()
$("#SelectedVender").on("change", function ()
$("#SelectedvendorText").val($(**"#SelectedVender option:selected"**).text());
);
);
【讨论】:
【参考方案9】:简单的解决方案不确定这是否已被建议。这也可能不适用于某些事情。话虽这么说,这是下面的简单解决方案。
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)
您也可以对数据库驱动的选择列表执行类似的操作。您需要在控制器中设置 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 );
【讨论】:
以上是关于如何在 MVC 的控制器中获取 DropDownList SelectedValue的主要内容,如果未能解决你的问题,请参考以下文章
如何在spring mvc控制器中获取getServletContext()
如何在 Asp.net core mvc 的控制器中获取自己的用户
如何从 mvc 控制器获取列表以使用 jquery ajax 查看