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).
Related
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 :)
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.
I have MVC3 website with edit form. On this form there is DropDownList that shows list of values that can be chosen. I want it to be set at previously selected value(on create form). This value is in Model.Status. I thought that this code would work:
#Html.DropDownList("Status",
new SelectList(ViewBag.Status as System.Collections.IEnumerable, "Id", "Status", Model.Status))
But the DropDownList is always set on first value from the list. I have checked - the correct value is in Model.Status.
Value of Model.Status is an id of status from list. ViewBag.Status is a list with id and string description - Status.
How to make it show the right value?
Any help much appreciated!
Have you checked this bug
Avoid to use same name of DropDownListand SelectList.
#Html.DropDownListFor(x=>x.SelectedItemId,
new SelectList(ViewBag.Status as System.Collections.IEnumerable,"Id",
"Status"),"Select Item")
But If i am writing this code, i would get rid of the ViewBag and change that to use another strongly typed object
public class YourMainViewModel
{
public int ID { set;get;}
public int SelectedItemId { set;get;}
public IEnumerable<Item> Items();
//other properties
}
public class Item
{
public int Id { set;get;}
public string Status { set;get;}
}
Instead of sending the collection in Viewbag, i would use my new model properties now
public ActionResult EditUser(int id)
{
var user=myRepositary.GetUser(id);
user.Items=myRepositary.GetAllItems();
user.SelectedItemId=5; // replace with the value from your database here,
}
Now in my View which is strongly typed to YourMainViewModel, I will write this
#Html.DropDownListFor(x=>x.SelectedItemId,
new SelectList(Model.Items,"Id",
"Status"),"Select Item")
Here is some sample code that you can modify and use in your scenario. I have an Edit view, on this view are a list of banks in a dropdown, and the bank that is associated with this application is already pre-selected in the list.
My view:
#model MyProject.ViewModels.MyViewModel
My banks dropdown:
<td><b>Bank:</b></td>
<td>
#Html.DropDownListFor(
x => x.BankId,
new SelectList(Model.Banks, "Id", "Name", Model.BankId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.BankId)
</td>
My MyViewModel:
public class MyViewModel
{
// Partial class
public int BankId { get; set; }
public IEnumerable<Bank> Banks { get; set; }
}
My Edit action method:
public ActionResult Edit(int id)
{
// Get the required application
GrantApplication application = grantApplicationService.FindById(id);
// Mapping
MyViewModel viewModel = (MyViewModel)
grantApplicationMapper.Map(
application,
typeof(GrantApplication),
typeof(MyViewModel)
);
// BankId comes from my table. This is the unique identifier for the bank that was selected when the application was added
// Get all the banks
viewModel.Banks = bankService.FindAll().Where(x => x.IsActive);
return View(viewModel);
}
My bank class:
public class Bank
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
}
Doing it this way will have a selected value in your dropdown after the form has loaded.
I hope this helps :)
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())%>