3

I am new guy in ASP.NET MVC 4. I want to populate dropdownlist from database table BO where Column name is Id, Code, Name, OrgId. I want to bind two Code & Namecolumn's data to DataTextfield and Id column Data to DataValueField of dropdown. I have created code for this which are as follows BUT ITS NOT RETURNING DATA FROM TABLE and var BOList is remain empty :

my connectionstring is 


 <add name="iRegDBContext"
  connectionString="Data Source=****;Initial Catalog=iReg;User ID=**;Password=****;Integrated Security=True"
  providerName="System.Data.SqlClient"
/>

My Controller class :

public class iRegController : Controller
{
    private iRegDBContext l_oDbBO = new iRegDBContext();  

    // GET: /iReg/

    public ActionResult PopulatejQgrid()
    {
        var BOList = l_oDbBO
                     .BO
                     .ToList()
                     .Select(d => new SelectListItem
                         {
                             Value = d.Id.ToString(),
                             Text = d.Name + "[ " + d.Code + " ]"
                         });
        ViewBag.BOData = new SelectList(BOList, "Value", "Text"); 
        return View();
    }
}

My Model class :

public class BO
{
    public Guid Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
}

public class iRegDBContext : DbContext
{
    public DbSet<BO> BO { get; set; }
}

My cshtml class :

@model MvciReg.Models.BO

@{
    ViewBag.Title = "PopulatejQgrid";
}

@using (Html.BeginForm())
{
    <fieldset>
        BO : 

        @Html.DropDownList("BOData")
        <p>
            <input type="submit" value="Go" />
        </p>
    </fieldset>
}

I really don't know where I am going wrong. I developed my code from reference of following link Click here . Kindly suggest correction in code ...

UPDATE: I tried following Matt Bodily's code in my controller and what I see is code is not fetching data from database and that code is

    public ActionResult populatejQgrid()
    {
        ViewBag.BOData = GetDropDown();

        return View();
    }

    public static List<SelectListItem> GetDropDown()
    {
        List<SelectListItem> ls = new List<SelectListItem>();
        var lm = from m in db.BOs //fetch data from database
                 select m;
        foreach (var temp in lm)
        {
            ls.Add(new SelectListItem() { Text = temp.Name, Value = temp.Id.ToString() });
        }
        return ls;
    }

In Controller :

      @Html.DropDownList("BOData", (List<SelectListItem>)ViewBag.BOData)

But when I saw value of ls through watch it always show me Count = 0 but its not giving me any error.

I found something new this problem. When I kept mouse pointer over var lm; it shows me query and in query table name in FROM clause is not that one in my SQL database. My SQL table name is BO and in query it is taking BOes. I don't know from where this name is coming. I think this is the main cause of all this problem So How I overcome this??

8
  • @Html.DropDownList("BOData"): it just defined a drop down controll with the name. try using @Html.DropDownListFor(m=>m.Id, new SelectList(ViewBag.BOData,"Value", "Text")) in the view Commented Oct 12, 2013 at 11:09
  • Is there any rule that you have to give TableName to class name or DbContext class name???? Commented Oct 12, 2013 at 11:12
  • Your are using EF/nhibernate? Code first? Commented Oct 12, 2013 at 11:13
  • My Controller's variable var BOList is remain empty. So How do I get data into this variable?? Commented Oct 12, 2013 at 11:15
  • Before trying on drop down start on text box and label. You need to fetch the table content in the class. Commented Oct 12, 2013 at 11:17

4 Answers 4

3

First Create a BO list for Dropdownlist in VIEW

@{
    var Bolst= Model.BO.Select(cl => new SelectListItem
       {
           Value = cl.Value.ToString(),
           Text = cl.Text== null ? String.Empty : cl.Text
       });
}

@(Html.DropDownList("sampleDropdown", BOlst, "-----Select-----"))

In Controller:

    return View(BOlst); // why use Viewbag when directly pass it to view
Sign up to request clarification or add additional context in comments.

Comments

0

from what I see in your code you are creating the select list and setting the ViewBag.BOData on the controller. So in order to render it on the view you should do this

@Html.DropDownList(ViewBag.BOData)

instead of

@Html.DropDownList("BOData")

Regarding the access to the database are you trying to use "code first" in an existing database? If you are you need to override the context constructor like this

public class iRegDBContext : DbContext
{
  public iRegDBContext()
     :base("Name= iRegDBContext")
   {
   }
}

see this link http://msdn.microsoft.com/en-us/data/jj200620.aspx

Hope it helps.

2 Comments

Please can you tell me, Why did you use public iRegDBContext() :base("Name= iRegDBContext") What's the meaning and use of this???
When you are using "Code First" trying to connect to an existing Database you need to tell entity framework to use that database otherwise it will create a database called iRegDBContext + hash. you can see it all in the link I posted in the answer.
0

try building your dropdown this way

@Html.DropDownList(x => x.Selected, PathToController.GetDropDown())

and then in your controller

public static List<SelectListItem> GetDropDown()
{
    List<SelectListItem> ls = new List<SelectListItem>();
    lm = (call database);
    foreach (var temp in lm)
    {
        ls.Add(new SelectListItem() { Text = temp.name, Value = temp.id });
    }
    return ls;
}

Hopefully this helps

2 Comments

:Thanx to take interest my question and for your suggestion. But VS showing me red underline to PathToController. What should i do for this??
type in your controller name and type ctrl-. this will bring in the full path to your controller (project, area, etc)
0

I recently had this issue also and managed to get it working using Viewbag. You will need to make it fit your Db tables but it works and is quite simple.

Populating Drop Down Box with Db Data

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.