TechGuy
TechGuy

Reputation: 4560

Unable to get @Html.DropDownListFor Selected Value

Here i have a Dropdownlistfor my project.But here i'm stucking with get selected value.my try is below.But still unable to get a Selected Item from Dropdownlist

@Html.DropDownListFor(m => m.ProductType, (SelectList)ViewBag.ListOfCategories, new { @class = "form-control"})

Model Code

[Required]
        public string ProductType { get; set; }

Controller

 [HttpPost]
    public ActionResult AddProduct(ICS.Models.ProductsModels.Products model)
    {
        ProductController _ctrl = new ProductController();
        _ctrl.AddorUpdateProduct(new ICS.Data.Product
        {
            ProductName = model.ProductName,
            ProductType = model.ProductType,
            IsFixed = model.PriceSettings,
            ItemPrice = model.ItemPrice,
            PurchasePrice = model.PurchasePrice,
            Vat = model.Vat,
            WholeSalePrice = model.WholeSalePrice,
            Comments = model.Comments
        });
        return View(model);
    }


[HttpGet]
    public ActionResult AddProduct()
    {
        ViewBag.ListOfCategories = new SelectList(_cat.GetCategory(), "CategoryId", "CategoryName");
        return View();
    }

Upvotes: 0

Views: 487

Answers (1)

Dmytro
Dmytro

Reputation: 17156

I suggest that Razor just do not understand what is text and what has to be value in your drop down list options so it just generates empty drop down (no value attribute). U can check your rendered html, I suppose it looks like

<select>
   <option>Category1Name</option>
   <option>Category2Name</option>
   <option>Category3Name</option>
   ...
</select>

U should use IEnumerable<SelectListItem> as a source for your drop down. Example:

[HttpGet]
public ActionResult AddProduct()
{
    // this has to be the list of all categories you want to chose from
    // I'm not shure that _cat.GetCategory() method gets all categories. If it does You
    // should rename it for more readability to GetCategories() for example
    var listOfCategories = _cat.GetCategory();

    ViewBag.ListOfCategories = listOfCategories.Select(c => new SelectListItem {
        Text = c.CategoryName,
        Value = c.CategoryId
    }).ToList();

    return View();
}

Upvotes: 1

Related Questions