Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 5 DropDownListFor Database Linq;

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

like image 282
user2117713 Avatar asked Mar 05 '26 18:03

user2117713


1 Answers

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.

like image 66
markpsmith Avatar answered Mar 08 '26 02:03

markpsmith