Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning int value from @html.DropDownList

Actually I have some problem which happened because of lack of my knowledge in ASP.NET - MVC 4. What I am trying to do is getting the selected value from the drop down and return it to the controller (as integer). What makes me more confuse is the other DropDownList which are returning string Value is working fine.

My model :

public partial class PRODUCT
{
    public int ID { get; set; }
    public string PRODUCT_NAME { get; set; }
    public int CATEGORY_ID { get; set; }
    public string LANGUAGE { get; set; }
}

public partial class PRODUCT_CATEGORY
{
    public int ID { get; set; }
    public string CATEGORY_NAME { get; set; }
    public string LANGUAGE { get; set; }
}

My Controller : //populating ViewBag

ListProductCategory = new List<PRODUCT_CATEGORY>();
ListProductCategory = db.PRODUCT_CATEGORY.ToList();

IList<PRODUCT_CATEGORY> prodCategories = db.PRODUCT_CATEGORY.ToList();
IEnumerable<SelectListItem> selectListCategory =
     from c in prodCategories
     select new SelectListItem
     {
      Text = c.CATEGORY_NAME,
       Value = c.ID.ToString()
     };

ViewBag.ProductCategoryData = selectListCategory;

//create action

[HttpPost]
public ActionResult Create(PRODUCT product)
{
    if (ModelState.IsValid)
    {
        db.PRODUCTs.Add(product);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(product);
}

My View :

<div class="editor-label">
        @Html.LabelFor(model => model.CATEGORY_ID)
 </div>

 <div class="editor-field">            
   @Html.DropDownList("ProductCategories", new  SelectList(ViewBag.ProductCategoryData, "Value", "Text"))          
   @Html.ValidationMessageFor(model => model.CATEGORY_ID)
 </div>

The DropDown lsit is populated but the value of ProductCategories not being returnd, its returning 0 instead of the value.

Please help ..

like image 246
anevil Avatar asked Oct 22 '22 09:10

anevil


1 Answers

What other dropdownlists are returning strings? I bet the string they are returning is part of the model. Your model doesn't have a ProductCategories property. Try changing:

@Html.DropDownList("ProductCategories", new  SelectList(ViewBag.ProductCategoryData, "Value", "Text"))          

To:

@Html.DropDownList("CATEGORY_ID", new  SelectList(ViewBag.ProductCategoryData, "Value", "Text"))          
like image 62
ethorn10 Avatar answered Oct 24 '22 09:10

ethorn10