我有下拉列表,我已经从数据库中填写了。现在,我需要在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使用Request.Form,你的下拉名字是ddlVendor这样传递ddlVendor的关键在的FormCollection获得由形式公布了其价值:
Request
Request.Form
ddlVendor
string strDDLValue = Request.Form["ddlVendor"].ToString();
或使用FormCollection:
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)