Click here to Skip to main content
15,905,508 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
Dear Sir,
I am new in mvc and i want to bind dropdownlist in MVC 3.0. My Code is given below

tables

tbl_Modules
Module_Id,ModuleName,ModuleDescription

tbl_DocumentTypes
Document_Id,DocumentName,DocumentDescription,Module_Id

now i want to craete form to add document type and in form i want a dropdownlist with Module_Id as value,ModuleName as text.
SQL
public class DocumetRepository
    {

        InwardManagementEntities db = new InwardManagementEntities();
       
        public IQueryable<tbl_DocumentTypes> FindAllDocumentTypes()
        {
            return db.tbl_DocumentTypes;
        }
       
    }


public class DocumentTypeViewModel
    {
         ModuleRepository _modulerepository = new ModuleRepository();
        public tbl_DocumentTypes Document { get; private set; }
        public SelectList Modules { get; private set; }

        public DocumentTypeViewModel(tbl_DocumentTypes document)
        {
            Document = document;
            //var _modules = _modulerepository.FindAllModules().Select(d => new  {Module_Id= SqlFunctions.StringConvert((double?)d.Module_Id), Text = d.ModuleName });
             var _modules = _modulerepository.FindAllModules().Select(d => new SelectListItem() {Value= SqlFunctions.StringConvert((double?)d.Module_Id), Text = d.ModuleName });
             Modules = new SelectList(_modules, Document.Module_Id);
        }
    }

And in conroller

SQL
public ActionResult AddDocument()
       {
           tbl_DocumentTypes _document = new tbl_DocumentTypes();

           return View(new DocumentTypeViewModel(_document));
       }



and in view
SQL
<div class="editor-label">
           Module
        </div>
        <div class="editor-field">
            @Html.DropDownList("Document.Module_Id", Model.Modules.ToList())
            @Html.ValidationMessageFor(model => model.Document.Module_Id)
        </div>



but in dropdownlist i get System.Web.Mvc.SelectListItem . Please help me
Posted

Maneesh you are using @Html.DropDownList instead of @Html.DropDownListFor helper. Look into this article

Binding drop down list in mvc 3[^]
 
Share this answer
 
Please read below mentioned article which I have written about how to bind viewmodel with dropdwonlist.

sample code :
SQL
@Html.DropDownListFor(m => m.SelectedValue,new SelectList(Model.ProductCategories, "Id","CategoryName"),"-Please select a category -")


How to Use ViewModel with ASP.NET MVC ?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900