我正在尝试使用Html.DropDownListFor来构建下拉列表并获取用户选择的值。我可以显示列表,但无法弄清楚如何获取链接以传递所选值 我有以下型号:
public partial class ProductVariant
{
public int ID { get; set; }
public string Sku { get; set; }
}
以下ViewModel:
public class SkuToDiscountViewModel
{
public int ID { get; set; }
public string Sku { get; set; }
public IEnumerable<ProductVariant> Products { get; set; }
}
以下控制器操作:
public ViewResult Index()
{
SkuToDiscountViewModel sModel = new SkuToDiscountViewModel();
List<ProductVariant> prodSkus = db.ProductVariants.ToList();
sModel.Products = prodSkus;
return View(sModel);
}
以下观点:
@model mySpace.ViewModel.SkuToDiscountViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using(Html.BeginForm())
{
Html.DropDownListFor(x=>x.ID,
new SelectList(Model.Products,"ID", "Sku", Model.ID), " select ")
<p>
@Html.ActionLink("Edit", "Edit")
</p>
}
感谢任何帮助。
答案 0 :(得分:2)
您需要提交表单的提交按钮:
@model mySpace.ViewModel.SkuToDiscountViewModel
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using(Html.BeginForm())
{
Html.DropDownListFor(x=>x.ID,
new SelectList(Model.Products,"ID", "Sku", Model.ID), " select ")
<p>
<input type="submit" value="Save" />
</p>
}
然后你需要像你一样向你的控制器添加一个Action:
[HttpPost]
public ActionResult Index(SkuToDiscountViewModel postedModel)
{
// postedModel.ID will contain the value selected in the drop down list
}