0

This is My Model

public class InsertOrder
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }     
}

public List<InsertOrder> getcustomerid()
{
    List<InsertOrder> customerlist = new List<InsertOrder>();
    SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString);
    SqlDataReader Datareader;
    {
        using (SqlCommand command = new SqlCommand("SELECT CustomerID,FirstName FROM customers", connection))
        {
            connection.Open();
            Datareader = command.ExecuteReader();
            while (Datareader.Read())
            {
                InsertOrder ID = new InsertOrder();
                ID.CustomerId = Convert.ToInt32(Datareader["CustomerID"]);
                ID.CustomerName = Datareader["FirstName"].ToString();

                customerlist.Add(ID);
            }
            Datareader.Close();
            return customerlist;
        }
    }
}

How to give in the view page

4
  • My answer here might be of some use to you. Commented Nov 13, 2014 at 11:21
  • Whats the model that contains the property you want to bind the selected InsertOrder to? Commented Nov 13, 2014 at 11:47
  • To bind value to a Dropdownlist @StephenMuecke Commented Nov 13, 2014 at 11:57
  • @jabi, Your not understanding. You need a model with a property to bind the selected InsertOrder to. In Moksh's answer below, it assumes you have a model with a property int SampleDropDownValue so the CustomerID value of the selected InsertOrder is bound to the value of SampleDropDownValue Commented Nov 13, 2014 at 22:29

1 Answer 1

0
            public ActionResult Index()
            {
                var customerList = new InsertOrder().getcustomerid();

                ViewBag.CustomerList = new SelectList(customerList, "CustomerId",CustomerName") ;
                return View(YourModel);
            }

At View

@Html.DropDownListFor(m => m.SampleDropDownValue, Model.CustomerList , "--Select--")
Sign up to request clarification or add additional context in comments.

1 Comment

You can avoid the for loop: ViewBag.CustomerList = new SelectList(customerList, "CustomerId", "CustomerName")

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.