我有下拉列表,我从数据库中填充了它。现在我需要在 Controller 中获取选定的值进行一些操作。但没有得到这个想法。我试过的代码。
型号
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
}
Controller
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.Form
从 Request
读取它,您的下拉名称是 ddlVendor
所以传递 ddlVendor
在 formCollection 中键入键以获取由表单发布的值:
string strDDLValue = Request.Form["ddlVendor"].ToString();
或使用FormCollection
:
[HttpPost]
public ActionResult ShowAllMobileDetails(MobileViewModel MV,FormCollection form)
{
string strDDLValue = form["ddlVendor"].ToString();
return View(MV);
}
第二种方法(通过模型):
如果你想绑定(bind)模型,那么在模型中添加一个属性:
public class MobileViewModel
{
public List<tbInsertMobile> MobileList;
public SelectList Vendor { get; set; }
public string SelectedVendor {get;set;}
}
在 View 中:
@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)
关于c# - 如何在 MVC 的 Controller 中获取 DropDownList SelectedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901175/