Use Html.DropDownListFor to get a selected value

2019-09-03 07:34发布

问题:

I am trying to use Html.DropDownListFor to build a dropdown list and get the user selected value. I can get the list to display but cannot figure out how to get the link to pass the selected value.
I have the following model:

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

The following ViewModel:

public class SkuToDiscountViewModel
{
    public int ID { get; set; }
    public string Sku { get; set; }
    public IEnumerable<ProductVariant> Products { get; set; }
}

The following Controller action:

public ViewResult Index()
    {
       SkuToDiscountViewModel sModel = new SkuToDiscountViewModel();
        List<ProductVariant> prodSkus = db.ProductVariants.ToList();
        sModel.Products = prodSkus;
        return View(sModel);
    }

The following view:

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

Any help is appreciated.

回答1:

You need to a submit button to your form:

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

Then you need to add an Action to your controller like this:

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