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
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.
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)
}
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.
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>();
}
Related
I am trying to pull data from my database in my MVC Controller. This is the code I have but not sure if I'm doing this right using a LINQ query
public class EditProfileController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public IActionResult Index()
{
var listdata = db.Users.ToList().Select(x => new FE.Models.AspNetUsers
{
Id = x.Id,
// (repeat the same for all)
}).ToList();
}
}
Get error on Index:
EditProfileController.Index(): not all code paths return a value FE
and on db:
The name db does not exist in the current context
How can I pull data from a database table to create a list view? Should I use LINQ and if so what am I missing from my code above?
You are not returning anything you should return your list:
public class EditProfileController : Controller
{
public IActionResult Index()
{
var listdata = db.Users.ToList().Select(x => new FE.Models.AspNetUsers
{
Id = x.Id,
// (repeat the same for all)
}).ToList();
return Ok(listdata);
}
}
public class EditProfileController : Controller
{
public IActionResult Index()
{
List<FE.Models.AspNetUsers> listdata = new List<FE.Models.AspNetUsers>();
using(ApplicationDbContext db = new ApplicationDbContext())
{
listdata = db.Users.Select(x => new FE.Models.AspNetUsers
{
Id = x.Id,
// (repeat the same for all)
}).ToList();
}
return View(listdata)
}
}
I made a couple assumptions that you are trying to pass the list to a view rather than returning the list of AspNetUsers and your db context is working. Make sure in your view you declare the model like so:
#model IEnumerable<FE.Models.AspNetUsers>
I only work with VB (use C# converter) so here is how I get get a list of values from my DB:
Public Function Index()
dim listData as List(Of Users) = new List(Of Users)
Using db as new YourDB()
listData = db.Users.Select(Function(x) x.Id = id).ToList()
End Using
return listdata
End Function
Or you can just use an IQueryable of your model.
I am fairly new to MVC, and I've been reading a bit about ViewModels, but how do I go about sending two models to my View, where the queries are like so
public ActionResult Index(int Id)
{
var People = from a in db.Person
select a;
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new
{
a.Project.ProjectId,
a.Project.Name,
a.Project.Customer,
a.Project.TechProfile.Select(x => new
{
x.TechId,
x.Name,
x.Elements
}),
a.MemberId,
a.Role,
a.Start,
a.End
};
return View(People);
}
I was using #model IQueryable<GeoCV.Models.Person> before so I could use a #foreach in my View but I don't know how to get my other query to the View so I can get data from it too.
Update
And I'm making a custom class for my Data query, but I don't know how to set the property of TechProfile
Right now I have
public IEnumerable<TechProfile> ProjectTechProfile { get; set; }
In my custom class, but it doesn't work, so I guess I have to specify TechId, Name and Elements?
But how?
A ViewModel wraps around the 2 models you are getting with your 2 queries, so you can return it as a single object to your view. In your case we need to adress another issue first. You are returning an anonymous object in your data query.
This means, your data query needs to return a strongly typed object instead of an anonymous object.
Create a class for your data query:
public class MyCustomDataObject
{
public int ProjectId { get; set; }
//... map all properties as needed
}
then edit your data query to return this object:
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new MyCustomDataObject
{
ProjectId = a.Project.ProjectId,
//assign all properties
};
Now you need to create the actual ViewModel class:
public class MyViewModel
{
public IEnumerable<Person> Persons { get; set; }
public IEnumerable<MyCustomDataObject> Data { get; set; }
}
And after this you just need to assign the values to it in your Actionmethod:
public ActionResult Index(int Id)
{
var People = from a in db.Person
select a;
var Data = from a in db.Member
where a.Person.PersonId.Equals(Id)
select new MyCustomDataObject
{
ProjectId = a.Project.ProjectId,
//...
};
//store data of both queries in your ViewModel class here:
var vm = new MyCustomDataObject();
vm.Persons = People;
vm.Data = Data
//return ViewModel to View.
return View(vm);
}
And then declare it in your view: #model Namespace.Subfolder.MyCustomDataObject
You can use #Html.Action("actionName","controllerName") method in view. You can divide your original view into multiple partial view and then you can render that partial view with dynamic model binding using #Html.Action("actionName","controllerName") method.
For more details with sample code http://devproconnections.com/development/how-use-aspnet-mvc-render-action-helpers
You can have methods like below to get multiple model in single view
private IList<People> GetPeople()
{
return from a in db.Person
select a;
}
private IList<Data> GetData()
{
return from a in db.Member
where a.Person.PersonId.Equals(Id)
select new
{
a.Project.ProjectId,
a.Project.Name,
a.Project.Customer,
a.Project.TechProfile.Select(x => new
{
x.TechId,
x.Name,
x.Elements
}),
a.MemberId,
a.Role,
a.Start,
a.End
};
}
public ActionResult Index(int Id)
{
var MultipleModel = new Tuple<IList<People>,IList<Data>>(GetPeople(),GetData()) { };
return View(MultipleModel);
}
Here's a codeproject tutorial on the subject.
I'm trying to use the results of a LINQ query to create a dropdownlist in an MVC app. I'm using this answer as a reference. However, when I try to implement for my case I get the error: 'System.String' does not contain a property with the name 'SAMPLING_EVENT'
My code is as follows:
Controller
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
ViewBag.Title = "Sample Tracker Tool";
DateTime nineMonthsAgo = DateTime.Now.AddDays(-270);
var context = new EDMS_Entities();
var resultSet = (from samplingEvents in context.EDMS_SAMPLES
where samplingEvents.RECORD_CREATED_DATE >= nineMonthsAgo
orderby samplingEvents.SAMPLING_EVENT
select samplingEvents.SAMPLE_ID)
.Distinct();
var viewModel = new SamplingEventsVM();
viewModel.SamplingEvents = new SelectList(resultSet, "SAMPLING_EVENT", "SAMPLING_EVENT");
return View(viewModel);
}
}
ViewModel class
public class SamplingEventsVM
{
public int SelectedSamplingEvent { get; set; }
public SelectList SamplingEvents { get; set; }
}
View
#model SamplingEventsVM
<h2>#ViewBag.Title</h2>
<span>
#Html.DropDownListFor(model => model.SelectedSamplingEvent, Model.SamplingEvents, "Sampling Event")
</span>
What am I doing wrong?
You are selecting this select samplingEvents.SAMPLE_ID
So you get a List of int maybe, depends on your ID type
Then you try to make a select list with the property value "SAMPLING_EVENT"
Which doesn't exist on the int object you filled resultSet with.
Instead do this:
var resultSet = (from samplingEvents in context.EDMS_SAMPLES
where samplingEvents.RECORD_CREATED_DATE >= nineMonthsAgo
orderby samplingEvents.SAMPLING_EVENT
select samplingEvents)
.Distinct();
i am new in mvc. so i populate dropdown this way
public ActionResult New()
{
var countryQuery = (from c in db.Customers
orderby c.Country ascending
select c.Country).Distinct();
List<SelectListItem> countryList = new List<SelectListItem>();
string defaultCountry = "USA";
foreach(var item in countryQuery)
{
countryList.Add(new SelectListItem() {
Text = item,
Value = item,
Selected=(item == defaultCountry ? true : false) });
}
ViewBag.Country = countryList;
ViewBag.Country = "UK";
return View();
}
#Html.DropDownList("Country", ViewBag.Countries as List<SelectListItem>)
i like to know how can i populate dropdown from model and also set default value. any sample code will be great help. thanks
Well this is not a great way to do this.
Create a ViewModel that will hold everything you want to be rendered at the view.
public class MyViewModel{
public List<SelectListItem> CountryList {get; set}
public string Country {get; set}
public MyViewModel(){
CountryList = new List<SelectListItem>();
Country = "USA"; //default values go here
}
Fill it with the data you need.
public ActionResult New()
{
var countryQuery = (from c in db.Customers
orderby c.Country ascending
select c.Country).Distinct();
MyViewModel myViewModel = new MyViewModel ();
foreach(var item in countryQuery)
{
myViewModel.CountryList.Add(new SelectListItem() {
Text = item,
Value = item
});
}
myViewModel.Country = "UK";
//Pass it to the view using the `ActionResult`
return ActionResult( myViewModel);
}
At the view, declare that this view is expecting a Model with type MyViewModel using the following line at the top of the file
#model namespace.MyViewModel
And at anytime you may use the Model as you please
#Html.DropDownList("Country", Model.CountryList, Model.Country)
You can't set the default value using Html.DropDownList, if you want to have a default value, the property itself should have a default value.
private string country;
public string Country
{
get { return country ?? "UK"; }
set { country = value; }
}
Then, when the drop down list renders, as long as "UK" is actually a value for one of the options, it will be automatically set to that.
If the DropDownList is filled in the controller and sent to the view via ViewBag, you can do:
ViewBag.MyName = new SelectList(DbContextname.Tablename, "Field_ID", "Description",idtobepresented);
I am developing MCV app with Razor syntax.
I have pass the elements to the dropdown list and I want to pass the any random item to the view, as oer than item , dropdown list item will be selected.
below code displays the dropdow code.
Controller Code
[SessionFilterAction]
public ViewResult Details(int id)
{
ViewBag.HODList = new SelectList(db.Employees.Where(e => e.DesignationType == "HOD"), "Id", "FullName");
ViewBag.ItemToBeSelectedInList = 5;
return View(paymentadvice);
}
View Code
if(ViewBag.DesignationTypeOfLoggedUser == "Staff")
{
#Html.DropDownList("HODList", String.Empty ,new { ???? })
}
Now I want to use viewbag element which will be select the one of the item of dropdown.
How to do this ?
There's a constructor of the SelectList class which allows you to specify the id of the item to be selected:
[SessionFilterAction]
public ViewResult Details(int id)
{
int itemToBeSelectedInList = 5;
ViewBag.HODList = new SelectList(
db.Employees.Where(e => e.DesignationType == "HOD"),
"Id",
"FullName",
itemToBeSelectedInList
);
return View(paymentadvice);
}
This being said, using ViewBag is bad practice and I would recommend you switching to using view models and strongly typed helpers in the view.
#Html.DropDownList selects item with flag Selected (SelectListItem.Selected = true).
SelectList has constructor which automatically set this flag for specified item:
public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)
selectedValue should be the id of the employee that will be selected :
var employees = db.Employees.Where(e => e.DesignationType == "HOD").ToList();
var selectedEmployeeId = employess[5].Id;
ViewBag.HODList = new SelectList(employees, "Id", "FullName", selectedEmployeeId );