how to select an item in selectlist in view model MVC 4

8.1k Views Asked by At

I am new in mvc 4 but getting progress. I'm getting crazy with something which how i can select an item in select list in view model. here is my controller code;

ViewBag.DepartmanListesi = new SelectList(VeriTabani.UnvanDepartmanlaris, "UDepId", "Departman");

and in my view model I am listing a diffirent database but in this list one field includes an id of the UnvanDepartmanlaris.instead of showing the id, I want to show name of the id. but what I have tried is not worked. can you please help me.

I searched many things but most of them was about how to set dropdownlist. I couldnt find any answer of my question.

Thank you in advance. I will be waiting for any response

2

There are 2 best solutions below

2
On BEST ANSWER

I'm using following approach. Hope it helps:

Create helper class (I'm having here all my selectlists)

Public static class Helper
{
public static List<SelectListItem> GetList()
        {
            var result = new List<SelectListItem>();
            var ctx = new YourContext();

            var items = from n in ctx.Clients
                        select new SelectListItem
                        {
                            Text = n.Client.Name,
                            Value = n.ClientID.ToString()
                        };

            foreach (var item in items)
                result.Add(item);
            return result;
        }
}

Than in your View:

@Html.DropDownList("GetClients", Helper.GetList())

Works for me.

0
On

Try this,

Controller

 public List<CustomerModel> GetCustomerName()
        {
            // Customer DropDown
            using (dataDataContext _context = new dataDataContext())
            {
                return (from c in _context.Customers
                        select new CustomerModel
                        {
                            CustomerId = c.CID,
                            customerName = c.CustomerName
                        }).ToList<CustomerModel>();
            }
        }

  [HttpGet]
        public ActionResult CustomerInfo()
        {

            var List = GetCustomerName();
            ViewBag.CustomerNameID = new SelectList(List, "CustomerId", "customerName");
            return View();
        }

View

@Html.DropDownList("CustomerId", (SelectList)ViewBag.CustomerNameID, "--Select--")

Model

public class CustomerModel
    {
        public int CustomerId { get; set; }

        public string customerName { get; set; }

        public List<SelectListItem> customerNameList { get; set; }
}