【问题标题】:Use Html.DropDownListFor to get a selected value使用 Html.DropDownListFor 获取选定的值
【发布时间】:2013-01-28 18:39:05
【问题描述】:

我正在尝试使用 Html.DropDownListFor 来构建一个下拉列表并获取用户选择的值。我可以显示列表,但无法弄清楚如何让链接传递所选值。
我有以下型号:

public partial class ProductVariant
{
    public int ID { get; set; }
    public string Sku { get; set; }
}

以下视图模型:

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

感谢任何帮助。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    你需要一个提交按钮到你的表单:

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

    然后你需要像这样向你的控制器添加一个动作:

    [HttpPost]
    public ActionResult Index(SkuToDiscountViewModel postedModel)
    {
        // postedModel.ID will contain the value selected in the drop down list
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多