alikuli
alikuli

Reputation: 546

How can I capture the @Html.DropDownListFor selected value?

I am using MVC5, Razor, Entity Framework, C#. I am trying to pass a value of a dorpdown list using a link.

my model is

public class TestVM
{
    public string TheID { get; set; }
}

I am loading an enum into a IEnumerable<SelectListItem>.

My enum is

public enum  DiscountENUM
{
     SaleCustomer,
     SaleCustomerCategory,
     SaleProduct,
     SaleProductCategory,
     SaleCustomerAndProduct,
     SaleCustomerAndProductCategory,
     SaleCustomerCategoryAndProductCategory,
     PurchaseVendor,
     PurchaseVendorAndProduct,
     PurchaseVendorAndProductCategory,
     PurchaseProduct,
     PurchaseProductCategory,
     Unknown
}

I am using the index method of the home controller

public ActionResult Index()
{
    ViewBag.ListOfDiscounts = SelectListDiscountENUM();
    TestVM d = new TestVM();
    return View(d);
}

Where I load the ListOfDiscounts using:

private IEnumerable<SelectListItem> SelectListDiscountENUM()
{
    List<SelectListItem> selectList = new List<SelectListItem>();
    var listOfEnumValues = Enum.GetValues(typeof(DiscountENUM));

    if (listOfEnumValues != null)
        if (listOfEnumValues.Length > 0)
        {
            foreach (var item in listOfEnumValues)
            {
                SelectListItem sVM = new SelectListItem();
                sVM.Value = item.ToString();
                sVM.Text = Enum.GetName(typeof(DiscountENUM), item).ToString();
                selectList.Add(sVM);
            }
        }

     return selectList.OrderBy(x => x.Text).AsEnumerable();
}

My create method which is called from the view is

public ActionResult Create(TestVM d, string TheID)
{
    return View();
}

My Index view is

@model ModelsClassLibrary.Models.DiscountNS.TestVM

<div>@Html.ActionLink("Create New", "Create", new { TheID = Model.TheID})</div>
<div>
    @Html.DropDownListFor(x => x.TheID, @ViewBag.ListOfDiscounts as IEnumerable<SelectListItem>, "--- Select Discount Type ---", new { @class = "form-control" })
</div>

The problem is in the following line in the View

<div>@Html.ActionLink("Create New", "Create", new { TheID = Model.TheID })</div>

I have tried adding a model with the name of the field as "TheID"... no luck. Also, added a string field in the parameter, no luck. I looked at the FormControl object, and there was nothing in it either! I suspect something has to be added at the Route level in the helper, but I don't know what.

Model.TheID is always null. Even when I select an item in the DropDownListFor.

Does anyone have an idea how I can capture the select value of the DropDownListFor and send it into the Html.ActionLink TheID?

Upvotes: 0

Views: 264

Answers (0)

Related Questions