After several days of reading on how to fill a listbox with linq i am completely lost on what I have to do to make this work. I know I have to have a viewmodel or something like that but since i cannot reference 2 models in the same view I don t know what to do.
this is the model i have
public class ABC
{
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public string d { get; set; }
public string Type { get; set; }
public int ID { get; set; }
public class ABCDBContext : DbContext
{
public DbSet<ABC> ABCs { get; set; }
}
}
public class ABCModel
{
public string type{ set; get; }
public List<ABC> ABCs { set; get; }
}
The controller i know i am missing a lot of things but I donĀ“t know how to fill the list with that linq query nor how to call this controller from the view without using beginform (I will have more than 1 listbox in this form )
public ActionResult GetStuff()
{
var Types = from m in db.ABCs
select m.Type.Distinct();
return View(Types);
}
And then on my view i am required to have
#model IEnumerable so i can show on that page everything that the table abc has.
So, can I create a viewModel that fills the lsitbox (I will need to fill at least 6 with the parameters that abc has so the user can search for abcs with those values, but i suppose that if i can understand how to do 1 i can do it for 6) with what I want and that allows me to show the entries that abc has?
and this is the view ( i know a lot of things are wrong with it but its just to give an example)
#using (Html.BeginForm("getSelectedValues", "ABC", FormMethod.Get))
{
Type:#Html.DropDownList()
a:#Html.DropDownList()
b:#Html.DropDownList()
//and so on
<input type="submit" value="Filter" />
}
Pardon for my ignorance for any aspect i missed but i am new to asp net mvc 5, also if anyone could just guide me or send me a guide on what I have to do i would greatly appreciate it.
What I would recommend is you create a ViewModel named MYPAGENAMEViewModel.cs, then in that ViewModel you have all the 'model' / data that you need for the view.cshtml file.... i.e. something like the following:
public class MYPAGENAMEViewModel
{
public List<Types> MyTypes { get; set; }
public List<OtherTypes> MyOtherTypes { get; set; }
}
then in your action.
public ActionResult GetStuff()
{
MYPAGENAMEViewModel myViewModel = new MYPAGENAMEViewModel();
myViewModel.MyTypes = from m in db.ABCs
select m.Type.Distinct();
myViewModel.MyOtherTypes = from m in db.CBAs
select m.Type.Distinct();
return View(myViewModel);
}
then at the top of your view:
#model MYPAGENAMEViewModel
and then later in the view:
MyTypes<br />
#Html.DropDownListFor(model => model.MyTypes.TypeId, (SelectList)model.MyTypes.TypeName)
MyOtherTypes<br />
#Html.DropDownListFor(model => model.MyOtherTypes.TypeId, (SelectList)model.MyOtherTypes.TypeName)
I'm not totally sure what you're after but this might be the solution.
First off, you'd create a ViewModel, such as:
public class MyViewModel
{
List<ABC> abcs { get; set; } // Your database values that you're going to loop through
List<WhateverALookupShouldBe> aDropDownValues { get; set; }
List<WhateverBLookupShouldBe> bDropDownValues { get; set; }
// etc
}
Populate those values in your Data or Controller.
If you're looping through a list and submitting values back you'll want an editor for, so make a folder under your view folder called "EditorTemplates". Then add a cshtml file with the same name as your model, e.g. ABC.
On your main view you would have:
#model MyViewModel
#Html.EditorFor(model => model.abcs)
Now in your ABC Editor template you would write something like this for your drop down lists:
#model ABC
#Html.DropDownListFor(model => model.a, new SelectList(Model.aDropDownValues, "DataValueFieldName", "DataTextFieldName"));
When you submit it back you should have the data returned to you.
Related
I'am trying to view information from two tables in a view with the view model, but it does not work.
This gives two tables with information.
public class HeatImage
{
[Key]
public int ImageId { get; set; }
public string name { get; set; }
}
public class HeatingArea
{
[Key]
public int ID { get; set; }
public string Area { get; set; }
}
My viewmodel
public class HeatingAreaViewModel
{
public IEnumerable<HeatImage> heatingImage { get; set; }
public IEnumerable<HeatingArea> heatingArea { get; set; }
}
My controller
public ActionResult Index()
{
HeatingAreaViewModel mymodel = new HeatingAreaViewModel();
mymodel.heatingArea = db.HeatingAreas.ToList();
mymodel.heatingImage = db.HeatImages.ToList();
return View(mymodel);
}
And my view
#model IEnumerable<Project.Models.HeatingAreaViewModel>
#foreach (var item in Model)
{
#item.heatingArea
}
Error
The model item passed into the dictionary is of type
'Project.Models.HeatingAreaViewModel', but this dictionary requires a
model item of type
'System.Collections.Generic.IEnumerable`1[Project.Models.HeatingAreaViewModel]'.
The error message tells it: the View expects IEnumerable of HeatingAreaViewModel, while your controller action sends to the view only HeatingAreaViewModel.
So either correct the controller to send a list of HeatingAreaViewModel, or correct the view to expect only a single instance of HeatingAreaViewModel.
You are sending through appels and expecting oranges, that is why you getting the error.
In your controller you are sending through a single (one) instance of HeatingAreaViewModel. In your view you are making provision to except a list of HeatingAreaViewModel instances (more than 1).
Reading through your replies you want to use both HeatImage and HeatingArea in each loop iteration. You will need to change your view model to accommodate this. For example, create a view model that can accommodate both:
public class HeatViewModel
{
public HeatImage HeatImage { get; set; }
public HeatingArea HeatingArea { get; set; }
}
You will pass this HeatViewModel as a list to your view.
public ActionResult Index()
{
// This is just dummy code
HeatingViewModel model1 = new HeatingAreaViewModel();
// Populate the properties
model1.HeatImage = new HeatImage();
// Populate the properties
model1.HeatingArea = new HeatingArea();
HeatingViewModel model2 = new HeatingAreaViewModel();
// Populate the properties
model2.HeatImage = new HeatImage();
// Populate the properties
model2.HeatingArea = new HeatingArea();
// Now pass this list to the view
List<HeatingViewModel> models = new List<HeatingViewModel>();
return View(models);
}
In your view your code would look something like this:
#model List<Project.Models.HeatingViewModel>
#foreach (var item in Model)
{
<p>item.HeatImage.Name</p>
<p>item.HeatingArea.ID (I have used ID because I don't know what your Area looks like)</p>
}
This way you have both objects in a single loop. You will just have to go and figure out how you are going to populate them, this is where the bulk of the work will be done.
I also noticed that you you start your properties in the lower case, best practices start them with caps. For example:
public HeatImage heatImage { get; set; }
...should be...
public HeatImage HeatImage { get; set; }
I hope this helps :)
Your view is expecting an IEnumerable of HeatingAreaViewModel and it seems as though your only passing a single instance.
Change this
#model IEnumerable<Project.Models.HeatingAreaViewModel>
to this
#model Project.Models.HeatingAreaViewModel
Then you'll be able to loop through the heatingArea and heatingImage properties like this
#foreach (var item in model.heatingArea)
{
//what ever you need to do here
}
If your problem is, how to iterate in one loop through the two lists of HeatingImage and HeatingArea, in your view, you have to redo your viewModel:
public class HeatingAreaViewModel
{
public HeatImage heatingImage { get; set; }
public HeatingArea heatingArea { get; set; }
}
and then the controller action:
public ActionResult Index()
{
heatingAreas = db.HeatingAreas.ToList();
heatingImages = db.HeatImages.ToList();
List<HeatingAreaViewModel> myModel = heatingAreas.Zip(heatingImages, (a, b) => new HeatingAreaViewModel {HeatingArea = a, HeatImage = b})
return View(mymodel);
}
Then the View will work, as it is.
However, I strongly advice against doing it this way. You would have to ensure, that corresponding elements in the two lists are in reality corresponding to each other. Which is very prone to errors. If there is an underlying logic that ties these two lists together (some relationship on database tables), I would use that one to join the lists/tables together, instead.
Simply your Model in the view doesn't matches what you sent from controller action, so I think you need to change your view to be like this:
#model HeatingAreaViewModel
#foreach (var item in Model.heatingImage)
{
#item.heatingArea
}
I'm really stumped right now. I've been stuck with this problem for a number of days now and frankly, I'm getting sick and tired of it.
I have this database table: https://gyazo.com/9d1b014ecdba1e244c2f6957b6d9397c
(notice FlightsTable)
My goal is to populate a dropdown menu based on the values from the "Departure" section.
I've tried lots of things and yet I still cannot get to grips with it.
Here's my model:
public class FlightModel
{
public int FlightID { set; get; }
public string Departure { set; get; }
public string Arrival { set; get; }
public int NumberOfSeats { set; get; }
public int NumberOfFlights { set; get; }
}
Controller:
public ActionResult BookFlight()
{
return View();
}
FlightDBEntities (from the FlightsDBModel)
namespace Project_v3.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class FlightsDBEntities : DbContext
{
public FlightsDBEntities()
: base("name=FlightsDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<FlightsTable> FlightsTables { get; set; }
}
}
Screenshot of the files: http://gyazo.com/31b447387f349fbbe541f44a358c3096
How do I make the dropdown work in my view for BookFlight? I'm really struggling with this so step-by-step solutions so I can understand every step would be greatly appreciated. Please and thank you.
There are a few ways to do this, this is an example:
You'll need something that actually creates your selectlist:
public SelectList GetAsSelectList()
{
var depts = from f in db.FlightsTables
select new SelectListItem
{
Value = f.Departure,
Text = f.Departure
};
return new SelectList(depts, "Value", "Text");
}
If departures are held in their own table, then it would be better to select them from there, using the Id primary key field as the selectlist's value field
I've assumed that the selectlist will be shown on the same page as FlightModel. If this is the case, then your model needs a property for the selectlist:
public SelectList DepartureList { get; set; }
Your controller method needs to create a FlightModel instance, populate it with whatever you want to show (including the selectlist) and pass it to the View:
public ActionResult BookFlight()
{
var model = new FlightModel
{
DepartureList = GetAsSelectList()
};
return View(model);
}
Depending on what you want the user to do with the selectlist, you display it in the view like this:
#Html.DropDownList("Departure", Model.DepartureList)
In your controller, select the distinct departures
IEnumerable<string> departures = db.FlightsTables.Select(f => f.Departure).Distinct();
and assign to to a ViewBag property (or better, use a view model with a property for the SelectList)
ViewBag.DepartureList = new SelectList(departures);
and in the view (unsure what the property you want to bind to - you have not shown your model for the Booking)
#Html.DropDownListFor(m => m.YourProperty, (SelectList)ViewBag.DepartureList, "-Please select-")
I suspect you may need to modify your flight table. You have a ID column but the have a column for number of flights. Surely you would need information about departure and arrival times for each flight?
Edit
Further to comments, your booking model may look something like.
public class BookingVM
{
public List<FlightModel> FlightList { get; set; } // to display available flights
public string Departure { get; set; } // bind to DepartureList
public int FlightID { get; set; } // bind to FlightID in a dropdown that displays the arrival locations
public int Seats { get; set; } // number of seats booked
public SelectList DepartureList { get; set; } // unique departures
}
You would need to handle the .change() event of the Departure dropdownlist, use ajax to pass the selected departure to a controller method that returns the flightID and arrival locations (and probably the number of available seats for each flight) and use that to populate the second dropdownlist (bound to FlightID and displaying the arrival locations).
Trying to unpack some inherited code and I am new to ASP.NET. My question:
What is available in the controller from a post action in a dropdownlist in C# (ASP.NET MVC5)?
Here is what I have in the view:
#using (Html.BeginForm("SignUp", "Location", FormMethod.Post))
....
#Html.DropDownListFor(
model => model.Member.PillarId, new SelectList (Model.Pillars, "Id", "Title"))
Here is the MemberViewModel:
public class MemberViewModel : IValidatableObject{
public int? LocationId { get; set; }
public int? PillarId { get; set; }
}
Here is the Member model:
public class Member
{
public int Id { get; set; }
public string Name { get; set; }
public int? LocationId { get; set; }
public int? PillarId { get; set; }
public String PillarTitle { get; set; }
Here is the Member model constructor(s):
public Member() { }
public Member(MemberViewModel member)
{
PillarId = member.PillarId;
///
}
Here is the Controller
public ActionResult SignUp(MemberViewModel member){///}
My form is correctly pulling the information from the DB to display, as well as posting correctly to the DB via the Controller. I do not want to change the visual options for the user to choose from (i.e. I think ListBox is out?).
Rather, I want to assign both Member.PillarId as well as the Member.Title based on their choice and have it available in the Controller for non-DB operations.
What is currently available in the SignUp method in the Controller? Can I call Model.Pillars.Title? Is it member.PillarId.Pillars.Id? If not, how can I assign it dynamically based on the user choice?
There are views and modelviews flying around in this code, and I am not sure what is available...
SO has a bunch of answers on the DropDownList, so here's a sampling of articles that are somewhat related to what I am getting at...
* This answer
* ListBox
* ListBoxFor: not MVC dynamic
* SelectList Constructor: Not MVC
With a dropdownlist the only value that will come back is the value of the selected item when posting back.
If you want something else to come back you would need a hidden field on the page and bind a change event listener to the dropdown to set the title in the hidden field
public class MemberViewModel : IValidatableObject{
public int? LocationId { get; set; }
public int? PillarId { get; set; }
public string Title { get; set;}
}
#using (Html.BeginForm("SignUp", "Location", FormMethod.Post))
....
#Html.DropDownListFor(
model => model.Member.PillarId, new SelectList (Model.Pillars, "Id", "Title"))
#Html.HiddenFor(model => model.Title);
javascript
$('#idofdropdown').on('change', function()
{
var selectedTitle = $(this).find(":selected").text();
$('#Title').val(selectedTitle);
});
How to get selected title from a drop down list: Get selected text from a drop-down list (select box) using jQuery
Then in your controller your viewmodel will have the title text inside the Title string :)
Hi I'm struggling to find the correct approach on SO for what I am currently doing, so I thought I would ask.
Here is my simplified code:
The entities are nested types based on using them with EF CodeFirst and the ViewModel is being mapped with AutoMapper.
When posting the form the ModelState is not valid due to the dropdownlist being mapped to model.CourseId and displaying my Course data.. i.e. CourseId = 2, CourseList = Null, but also having the [Required] attribute, really only CourseId is required but I also needed a relevant error message.
I then thought that in my Create GET & POST actions the view should probably just have the CourseId but I still need to display it as a dropdown and populate it and I was unsure as how to do that correctly.
I may also not be understanding how this should be used correctly and if I even need CourseName, i.e. since the Course already exists in the database I just want a foreign key to it, which will still let me show the selected course.
I'm also planning to break out all this mapping and data setting in my controller actions into a separate service layer but at the moment its a small prototype.
// Entities
public class Recipe {
public int Id { get; set; }
public string Name { get; set; }
public Course Course { get; set; }
}
public class Course {
public int Id { get; set; }
public string Name { get; set; }
}
// View Model
public class RecipeCreateViewModel {
// Recipe properties
public int Id { get; set; }
public string Name { get; set; }
// Course properties, as primitives via AutoMapper
public int CourseId { get; set; }
public string CourseName { get; set; }
// For a drop down list of courses
[Required(ErrorMessage = "Please select a Course.")]
public SelectList CourseList { get; set; }
}
// Part of my View
#model EatRateShare.WebUI.ViewModels.RecipeCreateViewModel
...
<div class="editor-label">
Course
</div>
<div class="editor-field">
#* The first param for DropDownListFor will make sure the relevant property is selected *#
#Html.DropDownListFor(model => model.CourseId, Model.CourseList, "Choose...")
#Html.ValidationMessageFor(model => model.CourseId)
</div>
...
// Controller actions
public ActionResult Create() {
// map the Recipe to its View Model
var recipeCreateViewModel = Mapper.Map<Recipe, RecipeCreateViewModel>(new Recipe());
recipeCreateViewModel.CourseList = new SelectList(courseRepository.All, "Id", "Name");
return View(recipeCreateViewModel);
}
[HttpPost]
public ActionResult Create(RecipeCreateViewModel recipe) {
if (ModelState.IsValid) {
var recipeEntity = Mapper.Map<RecipeCreateViewModel, Recipe>(recipe);
recipeRepository.InsertOrUpdate(recipeEntity);
recipeRepository.Save();
return RedirectToAction("Index");
} else {
recipe.CourseList = new SelectList(courseRepository.All, "Id", "Name");
return View(recipe);
}
}
I fixed my particular problem just by doing the below.
[Required(ErrorMessage = "Please select a Course.")]
public int CourseId { get; set; }
// public string CourseName { get; set; }
public SelectList CourseList { get; set; }
The view will use the DropDownListFor helper to map the drop down to my CourseId and that's all I really needed.
On to another problem now with AutoMapper and why it is not mapping back to the Recipe entity in the POST Create action.
I probably first need to find a way to store the relevant Course name in the "CourseName" property.
I have a small form which the user must fill in and consists of the following fields.
Name (Text)
Value (Text)
Group (Group - Is a list of option pulled from a database table)
Now the Model for this View looks like so,
public string Name { get; set; }
public string Value { get; set; }
public int GroupID { get; set; }
Now the view is Strongly Typed to the above model.
What method would one use to populate the drop down list? Since the data is not contained within the Model (It could be contained in the Model) should we be using Temp/View data? A HTML Helper? What would be the ideal way to achieve this.
I use a viewmodel for this with a dictionary (I like mvc contrib's select box) containing all the properties something like:
class LeViewModel {
public string Name { get; set; }
public string Value { get; set; }
public int GroupID { get; set; }
public Dictionary<string, string> Groups {get; set;}
}
Then in your view you'll only need to do
<%: Html.Select(m => m.GroupId).Options(Model.Groups) %>
Hope it helps.
NOTE: this assumes you are using MVC2.
If I ever need a strongly typed drop-down (a list of countries in this case), I use 2 properties on my ViewModel.
public IEnumerable<SelectListItem> Countries { get; set; }
public int CountryID { get; set; }
I do a pre-conversion of my list to an IEnumerable<SelectListItem> in my action using code similar to this. (This assumes a country class with a name and unique ID).
viewModel.Countries = Repository.ListAll().Select(c => new SelectListItem { Text = c.Name, Value = c.ID });
Then in my strongly typed view, I use:
<%= Html.DropDownListFor(model => model.CountryID, Model.Countries) %>
This is great, because when you post back to a strongly typed action (receiving the same viewmodel back), the CountryID will be the ID of the selected country.
The other benefit, if they have an issue with the validation. All you need to do is repopulate the .Countries list, pass the viewmodel back into the view and it will automatically select the the correct value.
I like the following approach: Have a helper class that does this things for you, something like (pseudo):
class DropdownLogic {
public DropdownLogic(MyModel model) { /* blah */ }
public ListOfDropdownItems ToDropdown() {
/* do something with model and transform the items into items for the dropdownlist */
// f.e. set the item that matches model.GroupId already as selected
}
}
Add in your model:
public DropdownLogic Groups { get; set; }
And in your view:
<%=Html.Dropdown(Model.Groups.ToDropdown())%>