Populate single dropdown from two tables - c#

The scenario is:
Data is stored in database in project and neighbourhood tables both.
Now, i want to populate dropdown with project id and project name and neighbourhoodId and neighbourhood name.
i am right now sending through viewBag like this:
ViewBag.NeighbourhoodId = new SelectList(allNeighbourhood(), "Id", "NeighbourhoodName");
on view page, getting dropdown populated like this:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
Now,how to send another viewBag in this dropdownList.
Second ques, My dropdown is in partial view So, i am sending data to partial view like this:
#Html.Partial("_CommentBoxSection",new Neighbourhood())
how to send new Project()) along with neighbourhood. Is there any overload of partial where i can send both of them.
i have seen some posts relating to this title but they are something different
I have recently tried this:
public class ProjectAndNeighbourhoodListItemViewModel
{
public Project Project { get; set; }
public Neighbourhood Neighbourhood { get; set; }
public string ProjectName { get; set; }
public int Id { get; set; }
public bool IsSelected { get; set; }
// public IEnumerable<SelectListItem> ToSelectListItem { get; set; }
public SelectListItem ToSelectListItem()
{
return new SelectListItem
{
Text = Project.ProjectName,
Value = Neighbourhood.Id.ToString(),
Selected = IsSelected
};
}
}
and on view page directly,
#model #model IEnumerable<ProjectAndNeighbourhoodListItemViewModel>
#Html.DropDownList("Locations", Model.Select(m => m.ToSelectListItem()), "Select a location")
but getting System.ArgumentNullException value cannot be null i have no code in controller do i have to pass something in controller too

Do not use ViewBag to pass values to your view, use ViewModels instead, it is much cleaner. The ViewModel is also a good place to create your SelectListItems. Create or map the ViewModel in your controller.
// ViewModel for a single selectable entry
public class ProjectAndNeighbourhoodListItemViewModel {
public string ProjectName { get; set; }
public long NeighbourhoodId { get; set; }
public bool IsSelected { get; set; }
public SelectListItem ToSelectListItem() {
return new SelectListItem {
Text = ProjectName,
Value = NeighbourhoodId.ToString(),
Selected = IsSelected
}
}
}
In your Razor View:
#model IEnumerable<ProjectAndNeighbourhoodListItemViewModel>
#* Would be even better to use a wrapper model that contains the collection of list items as property! *#
#Html.DropDownList("Locations", Model.Select(m => m.ToSelectListItem()) , "Select a location")

Related

Why SelectList returning Null value in model when submitting post?

I'm trying to submit a form using Html helper like this:
#using (Html.BeginForm("Create", "Certificate", FormMethod.Post, new { enctype = "multipart/form-data", id = "complianceCertificate" }))
Onload of page, I'm binding the dropdown using HTML helper like this
#Html.DropDownListFor(model => model._DetailsOfOwner.Id, Model._DetailsOfOwner.Practices, "Select licensee name...", new { #class = "form-control tx-13 pd-2 has-check-valid", #name = "LicenseeId" })
#Html.ValidationMessageFor(model => model._DetailsOfOwner.Practices, "", new { #class = "text-danger has-error-valid" })
It loaded correctly
The problem is when submitting the form. It passes null value in model of SelectList.
Here is my class where select list located
public class _DetailsOfOwnerViewModel : BaseAddress
{
public int Id { get; set; }
public SelectList Practices { get; set; }
public string LicenseeName { get; set; }
public string RMLNo { get; set; }
public string ContactPerson { get; set; }
public string Telephone { get; set; }
public string Email { get; set; }
}
Thank you.
You cant return complete SelectList you need to select a single value from dropdown that will be returned to server. You should change your model.
Switch this
public SelectList Practices { get; set; }
to this
public string Practices { get; set; }
A dropdown list when an item has been chosen maps to a single value rather than a list of values so the model isn't being bound properly on submission. Try changing the type of Practicies to an int or a string.
Here, You are binding a dropdown from the model object and may b that's why you take SelectList for practices property. But when you receive form data using the post method at that time you have only a single value selected in the dropdown so you need int or string for that.
So there is two way to fix it:
Bind dropdown by using ViewBag, in which you will assign your list and replace
public SelectList Practices {get;set;}
to
public string Practices {get;set;}
and bind dropdown by using model._DetailsOfOwner.Practices property instead of model._DetailsOfOwner.Id.
OR another way is
You are binding the model._DetailsOfOwner.Id in the dropdown so simply you can get selected value from that property.

How to populate dropdown menu from my local hosted database?

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).

What is available in the controller from a post action in a dropdownlist

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 :)

Asp net MVC 5 and listbox with linq

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.

Asp.Net MVC Handle Drop Down Boxes that are not part of the Model

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())%>

Categories

Resources