MVC 5 DropDownListFor Database Linq;

7.4k views Asked by At

Can anyone please tell me how to write Controller for C# (public ActionResult DropList()) for Drop Down List generate Linq I want convert this SELECT DISTINCT CouName FROM Locations; to Linq for my drop down list dynamically generate.

Chtml page how do I write in @Html.DropDownListFor("") Models.Location

4

There are 4 answers

1
AudioBubble On BEST ANSWER

Assuming you model is named MyModel

Controller

public ActionResult Edit()
{
  var couriers = // get your couriers from the database using your query
  // Is better to assign this to a property in your view model, but ViewBag will do for now
  ViewBag.CourierList = new SelectList(couriers);
  var model = new YourModel();
}

View

@model YourModel
@using(Html.BeginForm())
{
  @Html.DropDownListFor(m => m.CouriersName, (SelectList)ViewBag.CourierList)
}
2
markpsmith On

This code will generate a select list from an IQueryable GetAll() method, or you could use it on your entity directly using from c in _context.Set<Location>()

public SelectList GetAsSelectList()
{
    var locs = from c in GetAll()
               select new
               {
                   Id = c.Id,
                   Name = c.Name
               };
   return new SelectList(locs, "Id", "Name");
}

Where Id is the Value field and Name is the Text field of the selectlist options.

This would be assigned to a model property:

var model = new MyModel
{
    LocationList = GetAsSelectList();
}

You would pass the model to your View, and use DropDownListFor:

@Html.DropDownListFor(x => x.MyModel.Location, Model.LocationList)

Your model would also have a Location property which you would set to display a default value if you wanted to do that.

1
Saket Kumar On

As far as i have understood, you can do something like this:

public ActionResult DropList()
{
    List<SelectListItem> objResult = new List<SelectListItem>();
    var result = dbContext.Locations.Select(x=>x.CouName).Distinct().ToList();
    foreach(var item in result)
    {
      SelectListItem temp = new SelectListItem();
      temp.Text = item;
      temp.Value = item;
      objResult.Add(temp);
    }

    ViewBag.DropdownResult = objResult;

    return View();

}

Dropdown in view:

@Html.DropDownListFor(m=>m.ModelLocations, ViewBag.DropdownResult  as List<SelectListItem>)

Please modify the code as per your need.

0
Lodlaiden On
using System.Web.Mvc;
...
public static List<SelectListItem> GetItemsForDisplay(string listName)
{
    //your data access function should return a list of objects
    return DAL.Table.SelectByName(listName)
        .Select(x=> new SelectListItem{Text=x.DisplayName, Value=x.ID})
        .ToList<SelectListItem>();
}