Question

this is my Model :

public partial class TAUX
    {
        public short CAT_ID { get; set; }
        public int C_GARANT { get; set; }

        [Required(ErrorMessage = "Taux est obligatoire")]
        public decimal POURC_TAUX { get; set; }
        public System.DateTime DATE_EFFET { get; set; }
        public int TAUX_ID { get; set; }

        public virtual CATEGORIE CATEGORIE { get; set; }
        public virtual GARANTIE GARANTIE { get; set; }

        public IEnumerable<int> SelectItems { set; get; }
    }

This is my Controller :

public ActionResult Create()
        {
            ViewBag.CAT_ID = new SelectList(db.CATEGORIE, "CAT_ID", "LIBELLE");
            ViewBag.C_GARANT = new SelectList(db.GARANTIE, "C_GARANT", "LIB_ABREGE");
            return PartialView("_Create");
        }

This is my View :

<div class="form-group">
            <label for="Categorie">Categorie : </label>
            @Html.ListBoxFor(model => model.SelectItems, "CAT_ID")
            @Html.ValidationMessageFor(model => model.CAT_ID)
         </div>

And this the error That I got :

Error 1 :'System.Web.Mvc.HtmlHelper<pfebs0.Models.TAUX>' does not contain a definition for 'ListBoxFor' and the best extension method overload 'System.Web.Mvc.Html.SelectExtensions.ListBoxFor<TModel,TProperty>(System.Web.Mvc.HtmlHelper<TModel>, System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>, System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)' has some invalid argument
Error   2: Argument 3: cannot convert from 'string' to 'System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>'

What I'm trying to do is getting all data from Categorie Tabel and put it in ViewBg.CAT_ID. Then In my View I have a listBox filled with Item From ViewBag.CAT_ID, and the selected Value Will be set in SelectItems.

Was it helpful?

Solution

Here is the issue.

@Html.ListBoxFor(model => model.SelectItems, "CAT_ID")

The second argument should be the select list rather than a string, so it should be like

@Html.ListBoxFor(model => model.SelectItems, (ViewBag.CAT_ID as SelectList)) 

OR

@{
 var list = ViewBag.CAT_ID as SelectList;
}

@Html.ListBoxFor(model => model.SelectItems, list ) 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top