Witejcie ponownie.
Tym razem nie wiem jak rozwiązać problem przesyłania kategorii z bazy danych do EnumDropDownList a następnie po wybraniu jakiejś w widoku przekazania jej do akcji kontrolera.
W moim widoku mam:
<div class="form-group">
@Html.LabelFor(model => model.ProductCategory, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.ProductCategory, (IEnumerable<SelectListItem>)ViewBag.categories)
@Html.ValidationMessageFor(model => model.ProductCategory, "", new { @class = "text-danger" })
</div>
</div>
Natomiast w Controllerze chce jakoś przesłać to ViewBagiem
// tutaj przekazuje wszystkie kategorie do drop down listy
public ActionResult AddNewProduct()
{
var categories =
_categoryService.GetAllCategories()
.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
ViewBag.categories = categories;
return View();
}
// tutaj tworzy sie nowy produkt i nie wiem jak ta wybraną kategorie przekazać z drop down listy do pola ProductCategory
[HttpPost]
public ActionResult AddNewProduct(NewProductViewModel newProd, HttpPostedFileBase file)
{
using (var db = new ApplicationDbContext())
{
var product = new Product
{
ProductName = newProd.ProductName,
ProductImageUrl = newProd.ProductImageUrl,
Category = _categoryService.GetAllCategories().ToList(),
ProductDescription = newProd.ProductDescription,
PricePerUnit = newProd.ProductPrice,
ProductQuantity = newProd.ProductQuantity,
PremiumPoints = newProd.PremiumPoints,
NutritionalValues = new NutritionalValue
{
Calorific = newProd.ProductCalorific,
Carbohydrate = newProd.ProductCarbohydrates,
Protein = newProd.ProductProteins,
Fat = newProd.ProductFat
},
Suplier = new Suplier
{
CompanyName = newProd.ProductSuplierName,
Address = new Collection<Addresses>
{
new Addresses()
{
Country = newProd.ProductSuplierCountry,
City = newProd.ProductSuplierCity,
StreetName = newProd.ProductSuplierStreetName,
PostalCode = newProd.ProductSuplierPostalCode,
FlatNumber = newProd.ProductSuplierFlatNumber
}
}
}
};
if (ModelState.IsValid)
{
if (file == null)
return View();
var pic = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Images/Products/"), pic);
file.SaveAs(path);
product.ProductImageUrl = path;
using (var ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
}
_productService.InsertProduct(product);
return RedirectToAction("Index", "Home");
}
}
return View();
}
Otrzymuje dziwny błąd:
Return type 'System.Int32' is not supported.
Nazwa parametru: expression
Dokładnie w widoku w tej linii:
@Html.EnumDropDownListFor(model => model.ProductCategory, (IEnumerable<SelectListItem>)ViewBag.categories)
Co robię zle? :(