Dynamiczne wczytywanie kategorii z bazy i przekazywanie ich do akcji i produktu

0

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? :(

0

Mój viewmodel

 
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web;
using AdamKawikSklepInternetowy.Models.Models;

namespace AdamKawikSklepInternetowy.ViewModels.ViewModels
{
    public class NewProductViewModel
    {
        // dane produktu
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Nazwa produktu")]
        public string ProductName { get; set; }

        [DataType(DataType.ImageUrl)]
        [Display(Name = "Miniatura produktu")]
        public string ProductImageUrl { get; set; }

        //wyswietlana bedzie nazwa kategorii, ale jak user wybierze jakas, to zostanie zapamietany jej ID, wiec musi byc to INT
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Nazwa kategorii")]
        public int ProductCategory { get; set; }

        [Required]
        [DataType(DataType.MultilineText)]
        [Display(Name = "Opis produktu")]
        public string ProductDescription { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Cena produktu")]
        public decimal ProductPrice { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Ilość produktów")]
        public int ProductQuantity { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Punkty premium")]
        public int PremiumPoints { get; set; }

        // dane dla wartosci odzywczych
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Kaloryczność")]
        public int ProductCalorific { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Węglowodany")]
        public int ProductCarbohydrates { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Białka")]
        public int ProductProteins { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name="Tłuszcze")]
        public int ProductFat { get; set; }

        // dane dla dostawcy
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Nazwa dostawcy")]
        public string ProductSuplierName { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Kraj dostawcy")]
        public string ProductSuplierCountry { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Miasto dostawcy")]
        public string ProductSuplierCity { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Kod pocztowy")]
        public string ProductSuplierPostalCode { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Ulica dostawcy")]
        public string ProductSuplierStreetName { get; set; }
        [Required]
        [DataType(DataType.Text)]
        [Display(Name = "Numer mieszkania")]
        public string ProductSuplierFlatNumber { get; set; }

     
    }
}

0

Nie tak dawno miałem całkiem podobny problem. Zerknij tutaj:
http://4programmers.net/Forum/C_i_.NET/241620-dropdownlist_-_zapis_elementu_do_bazy

0

Spoko już sobie poradziłem :) Bo na Was siędoczekać to masakra :D

0
Odyn napisał(a):

Spoko już sobie poradziłem :) Bo na Was siędoczekać to masakra :D

Jeśli Cię to interesuje, to za 1000 zł dziennie + VAT możesz u mnie wykupić usługę odpowiadania na posty w ciągu 15 minut w godzinach 9:00 - 19:00.

1 użytkowników online, w tym zalogowanych: 0, gości: 1