how to select data from multiple table using multiple dropdown and insert the selected values in one table in database in mvc - asp.net-mvc

Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Lecture timetable)
{
Lecture t = new Lecture();
ViewBag.SId = new SelectList(db.Sections, "Id", "SectionName");
ViewBag.CId = new SelectList(db.Course, "Id", "CourseName");
ViewBag.FId = new SelectList(db.Faculty, "Id", "FacultyName");
if (ModelState.IsValid)
{
db.TimeTable.Add(timetable);
db.SaveChanges();
return RedirectToAction("Create");
}
return View(timetable);
}
Model:
[Table("Lecture")]
public class Lecture
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Terms { get; set; }
public string Semester { get; set; }
public int SectionsId { get; set; }
[ForeignKey("SectionsId")]
public Sections Sections { get; set; }
public int CourseId { get; set; }
[ForeignKey("CourseId")]
public Course Course { get; set; }
public string CreditHourTheory { get; set; }
public string CreditHourLab { get; set; }
public int? LabInstructorId { get; set; }
[ForeignKey("LabInstructorId")]
public Faculty Labinstructor { get; set; }
public int FacultyId { get; set; }
[ForeignKey("FacultyId")]
public Faculty Faculty { get; set; }
public int RoomId { get; set; }
[ForeignKey("RoomId")]
public Rooms Rooms { get; set; }
public string Day { get; set; }
public DateTime Date { get; set; }
public TimeSpan TimeStart { get; set; }
public TimeSpan TimeEnd { get; set; }
}
View:
#Html.DropDownList("SId", null, String.Empty, new { #class = "form-control", #required = "" })
#Html.DropDownList("CId", null , String.Empty, new { #class = "form-control select-section", #required = "" })
#Html.DropDownList("FId", null , String.Empty, new { #class = "form-control select-section", #required = "" })
This is the form with dropdown i want to select these values and after clicking the create button the selected values should be submitted in the table "Lecture" in database
i am getting some error in inserting the selected value in database. Kindly provide me a better solution for this problem. the values in the dropdown are coming from the database from different tables.

The Problem in your another function Create with attribute [HttpGet] (or without any attributes, by default [httpGet]).
Variables in ViewBag must be named as well as members of the class Lecture SectionsId, CourseId, FacultyId.
And you should make redirect to Edit Action.
So,
Controller:
public ActionResult Create()
{
ViewBag.SectionsId = new SelectList(db.Sections, "Id", "SectionName");
ViewBag.CourseId = new SelectList(db.Course, "Id", "CourseName");
ViewBag.FacultyId = new SelectList(db.Faculty, "Id", "FacultyName");
return View(new Lecture());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Lecture timetable)
{
ViewBag.SectionsId = new SelectList(db.Sections, "Id", "SectionName");
ViewBag.CourseId = new SelectList(db.Course, "Id", "CourseName");
ViewBag.FacultyId = new SelectList(db.Faculty, "Id", "FacultyName");
if (ModelState.IsValid)
{
db.TimeTable.Add(timetable);
db.SaveChanges();
return RedirectToAction("Edit");
}
return View(timetable);
}
View:
#Html.DropDownList("SectionsId", null, htmlAttributes: new {#id = "SectionsId", #class = "form-control"})
#Html.DropDownList("CourseId", null, htmlAttributes: new {#id = "CourseId", #class = "form-control"})
#Html.DropDownList("FacultyId", null, htmlAttributes: new {#id = "FacultyId", #class = "form-control"})

Related

Unable to cast object of type 'System.Collections.Generic.List`1 Models.Hospitals]' to type 'System.Collections.Generic.IEnumerable`

When click view in browser I got this error unable to cast object ... in MVC view ,
This is the Hospital Model:
public partial class Hospitals
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Hospitals()
{
this.hospital_orders = new HashSet<hospital_orders>();
}
public int hospital_id { get; set; }
public string hospital_name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<hospital_orders> hospital_orders { get; set; }
}
This is the hospital_orders models :
public partial class hospital_orders
{
public int order_id { get; set; }
public Nullable<int> hospital_id { get; set; }
public Nullable<int> department_id { get; set; }
public Nullable<int> employee_id { get; set; }
public Nullable<int> status_id { get; set; }
public string order_details { get; set; }
public Nullable<int> user_id { get; set; }
public Nullable<System.DateTime> order_date { get; set; }
public Nullable<System.DateTime> update_date { get; set; }
public Nullable<System.DateTime> deleted_date { get; set; }
public string file { get; set; }
public virtual Departments Departments { get; set; }
public virtual Employees Employees { get; set; }
public virtual Hospitals Hospitals { get; set; }
public virtual order_status order_status { get; set; }
public virtual Users_web Users_web { get; set; }
}
this is the controller create code :
public ActionResult Create()
{
var hospName = db.Hospitals.ToList();
List<SelectListItem> listhosp = new List<SelectListItem>();
foreach (var item in hospName)
{
listhosp.Add(new SelectListItem { Text = item.hospital_name, Value =
item.hospital_id.ToString()});
}
ViewBag.hospitalname = hospName;
return View();
}
this is the view code :
<div class="form-group">
#Html.LabelFor(model => model.Hospitals.hospital_name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Hospitals.hospital_id,(IEnumerable<SelectListItem>) ViewBag.hospitalname,"Select Hospital", new { #class = "form-control" } )
#Html.ValidationMessageFor(model => model.hospital_id, "", new { #class = "text-danger" })
</div>
</div>
The error appeared on the line with dropdownlistfor , How to solve this error ?
I found the solution , the error in Viewbag assignment it should be assigned to list
not to variable like the following :
public ActionResult Create()
{
var hospName = db.Hospitals.ToList();
List<SelectListItem> listhosp = new List<SelectListItem>();
foreach (var item in hospName)
{
listhosp.Add(new SelectListItem { Text = item.hospital_name, Value =
item.hospital_id.ToString()});
}
// ViewBag.hospitalname = hospName; error here
ViewBag.hospitalname = listhosp ;
return View();
}

Populate DropDownList in ASP.NET MVC from database table using Entity Framework 6 and ViewModel

I have been scratching my head for a whole night on an issue I can do quickly using ajax/jquery and stored procedures. I want to
1) Populate a drop down list from values obtained from a database table using Entity Framework and view model. I DO NOT WANT TO USE VIEWBAG OR VIEWDATA. Any help appreciated.
2) How can I generate a Create View using the View Model with the all the default fields ? The scaffholding works on a model but not on a view model ?
MY MODELS
public class Employee
{
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public string Level { get; set; }
public int DepartmentId { get; set; }
}
public class Grade
{
public int ID { get; set; }
public string Level { get; set; }
}
View Model
public class GradeSelectListViewModel
{
public Employee Employee { get; set; }
public IEnumerable<SelectListItem> Grades { get; set; }
public GradeSelectListViewModel(Employee employee, IEnumerable grades)
{
Employee = employee;
Grades = new SelectList(grades, "Grade", "Name", employee.Level);
}
}
MY CONTEXT CLASS
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Departments { get; set; }
public DbSet<Grade> Grades { get; set; }
}
MY CONTROLLER
public ActionResult Edit (int? id)
{
using (var db = new EmployeeContext())
{
var model = new GradeSelectListViewModel(db.Employees.Find(id), db.Grades);
//model.Employee = db.Employees.Single(x => x.EmployeeID == id);
model.Grades = db.Grades.ToList().Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Level
});
return View(model);
}
}
MY RAZOR PAGE CSHTML
#model MVCDemo.ViewModels.GradeSelectListViewModel
....
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
....
#Html.DropDownListFor(x => Model.Employee.Level,
new SelectList(Model.Grades, "ID", "Level"),
"Select Level")
....
<input type="submit" value="Create" class="btn btn-default" />
}
The main issue is that in the view you have new SelectList(Model.Grades, "ID", "Level") but Grades is IEnumerable<SelectListItem> and SelectListItem does not contain properties named ID and Level.
However there are a a few other issues with your code. First a view model should not contain a data model, and instead your view model should be
public class GradeSelectListViewModel
{
public int? ID { get; set; } // make this ID so you do not need an input for it
public string Name { get; set; }
.... // other properties of Employee that your editing
[Required(ErrorMessage = "..")]
public int? Level { get; set; } // make value types nullable to protect against under-posting attacks
public IEnumerable<SelectListItem> Grades { get; set; }
}
and add display and validation attributes as required. Note that I deleted the constructor (you don't seem to be using it, but if you did, then you also need to include a parameter-less constructor, otherwise an exception will be thrown when submitting to the POST method. I also assume that Level should be typeof int since you binding to the int ID property of Grade.
The the code in your GET method should be
Employee employee = db.Employees.Find(id);
var model = new GradeSelectListViewModel()
{
ID = employee.EmployeeID,
Name = employee.Name,
Level = employee.Level, // convert to int?
....
Grades = db.Grades.Select(x => new SelectListItem
{
Value = x.ID.ToString(),
Text = x.Level
})
};
return View(model);
and in the view
#Html.DropDownListFor(x => Model.Level, Model.Grades, "Select Level")
Note also that in the POST method, your need to reassign the SelectList if you return the view because ModelState is invalid.
You can use the following approach that populates three DropDownListFor at the same View:
ViewModel:
public class GroupViewModel
{
public IEnumerable<SelectListItem> Schedules { get; set; }
public int ScheduleId { get; set; }
public IEnumerable<SelectListItem> Labs { get; set; }
public int LabId { get; set; }
public IEnumerable<SelectListItem> Terms { get; set; }
public int TermId { get; set; }
}
Controller:
public ActionResult Create()
{
//Populate DropDownList binding values
var model = new GroupViewModel
{
//Preselect the Lab with id 2
//LabId = 2,
Labs = repository.Labs.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
}),
Terms = repository.Terms.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
}),
Schedules = repository.Schedules.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Name
})
};
return View("Create", model);
}
View:
#Html.DropDownListFor(m => m.LabId, new SelectList(Model.Labs, "Value", "Text"),
"Select", new { #class = "selectpicker" })
#Html.DropDownListFor(m => m.ScheduleId, new SelectList(Model.Schedules, "Value", "Text"),
"Select", new { #class = "selectpicker" })
#Html.DropDownListFor(m => m.TermId, new SelectList(Model.Terms, "Value", "Text"),
"Select", new { #class = "selectpicker" })

MVC ASP.net Multiple Views trying to store tags

Model:
public class PublishedSongViewModel
{
public int Id { get; set; }
[Required(AllowEmptyStrings = false)]
public string SongName { get; set; }
//...
[Required]
public IEnumerable<string> Category { get; set; }
}
public class CategoryViewModel
{
public short Id { get; set; }
public string Title { get; set; }
public virtual ICollection<SongCategoryViewModel> SongCategory { get; set; }
}
public class SongCategoryViewModel
{
public int Id { get; set; }
[Required]
public int PublishedSongId { get; set; }
[Required]
public short CategoryId { get; set; }
}
View:
#model IList<PublishedSongViewModel>
#using (Html.BeginForm("PublishMusic", "Publish", FormMethod.Post, new { #enctype = "multipart/form-data", #id = "form-upload" }))
{
#Html.DropDownListFor(x => Model[i].Category, new SelectList(//Categories list here), new { #class = "form-control dl_Categories ", Multiple = "Multiple" })
}
Controller:
[HttpPost]
public ActionResult PublishMusic(IEnumerable<PublishedSongViewModel> songDetails)
{
if (songDetails != null)
{
IEnumerable<PublishedSongViewModel> savedSongs = (IEnumerable<PublishedSongViewModel>)(Session["UserSongs"]);
var lookupDetails = songDetails.ToDictionary(song => song.Id, song => song);
if (savedSongs != null)
{
foreach (var publishedSong in savedSongs)
{
var key = publishedSong.Id;
if (lookupDetails.ContainsKey(key))
{
var details = lookupDetails[key];
publishedSong.SongName = details.SongName;
}
db.SongCategories.Add(new SongCategoryViewModel { PublishedSongId = key, CategoryId = //categories id that user typed in on editorFor});
db.PublishedSongs.Add(publishedSong);
db.SaveChanges();
}
}
}
return View("Index");
}
I'v filled CategoryViewModel table up with data in my SQL.
1) How do I get the titles of CategoryViewModel and pass them in the SelectList(//Here) parameter in my viewmodel?
2) In the PublishMusic Action, how do I get the CategoryId for the SongCategoryViewModel from the one or more categories that the user selected from songDetails.Category?
I am not sure if I am on the right track with this. basically the categories are like tags, the user can select more than one. I'v also cut out unessential code to make easier to read.

Dropdownlist in viewModel create view

I have a "Leads" table which has a one to many relationship to "Employees" table. I also have created a leadViewModel class because I need some additional info for the Lead (Like addresses and phones etc.)
Here is the Lead class:
public partial class Leads
{
[Key]
public int LeadID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
public string FullName { get { return FirstName + " " + LastName; } }
public int EmployeeID { get; set; }
public virtual Employees Employees { get; set; }
}
Employee Class:
public partial class Employees
{
public Employees()
{
this.Leads = new HashSet<Leads>();
}
[Key]
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
public string FullName { get { return FirstName + " " + LastName; } }
public virtual ICollection<Leads> Leads { get; set; }
}
leadViewModel:
public class LeadViewModel
{
public Leads _leads { get; set; }
public Addresses _addresses { get; set; }
public Phones _phones { get; set; }
public Emails _emails { get; set; }
public IEnumerable<SelectListItem> EmployeesSelectListItem { get; set; }
}
Now I want to have a dropdown list in the "Create" view. I am not sure what to do. Here is what I did and got errors.
LeadsController Create Get:
// GET: Leads/Create
public ActionResult Create()
{
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName");
return View();
}
LeadsController Create Post:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "_leads,_addresses,_phones,_emails,EmployeesSelectListItem")] LeadViewModel leadVM)
{
if (ModelState.IsValid)
{
using (TransactionScope leadScope = new TransactionScope())
{
db.Leads.Add(leadVM._leads);
db.SaveChanges();
leadScope.Complete();
return RedirectToAction("Index");
}
}
ViewBag.EmployeeID = new SelectList(db.Employees, "EmployeeID", "FirstName", leadVM._leads.EmployeeID);
return View(leadVM);
}
and finally the create view:
#model CL_AHR_CRM.ViewModels.LeadViewModel
...
<div class="form-group">
#Html.LabelFor(model => model._leads.EmployeeID, "EmployeeID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(x => x._leads.EmployeeID, new SelectList(Model.EmployeesSelectListItem, "EmployeeID", "FirstName"), htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model._leads.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
I repeat my question: How can I use dropdownliast in a view when using a viewModel like this because obviously what I have done is not the way and is not working. I get the error: "Object reference not set to an instance of an object." on the Html.DropdownlistFor(...) in create view.
Your view is based on typeof LeadViewModel but in the GET method you do not pass and instance of the model to the view, let alone populate the EmployeesSelectListItem property so in your DropDownListFor() method, new SelectList(Model.EmployeesSelectListItem, ... will throw and exception (the value of Model is null
Change the view model property to
public SelectList EmployeesSelectListItem { get; set; } // perhaps rename to EmployeeList?
Then change you GET method to
public ActionResult Create()
{
LeadViewModel model = new LeadViewModel();
model.EmployeesSelectListItem = new SelectList(db.Employees, "EmployeeID", "FirstName");
return View(model);
}
Similarly in the POST method you need to use
leadVM.EmployeesSelectListItem = new SelectList(db.Employees, "EmployeeID", "FirstName");
when you return the view (i.e when ModelState is invalid)
Then in the view use
#Html.DropDownListFor(x => x._leads.EmployeeID, Model.EmployeesSelectListItem, new { #class = "form-control" })

Get the ID of the selected item in Dropdown list

I have to save the ID of a selected item into the database. but, I always get a null value when I select an item from the dropdown.
Here is some code:
Controller:
public ActionResult Create()
{
SelectList CategoryList = new SelectList(dc.Category.ToList(), "ID", "CategoryName");
ViewData["Categories"] = CategoryList;
ViewData.Model = new AdvertModel();
return View();
}
View:
<%:Html.DropDownList("Categories", ViewData["Categories"] as SelectList, new { #class = "dropdown" })%>
MODEL: AdvertModel
public class AdvertModel
{
public Int32 ID { get; set; }
[Required(AllowEmptyStrings=false,ErrorMessage="Please enter the title of your Ad.")]
[Display(Name="Title")]
public string Title { get; set; }
[Required(AllowEmptyStrings=false,ErrorMessage="Please enter a description of your Ad.")]
[Display(Name = "Details")]
public string Details { get; set; }
[Required(AllowEmptyStrings=false,ErrorMessage="Please enter when your Ad. will be publish")]
[Display(Name = "Publish date")]
[DataType(DataType.Date)]
public DateTime PubDate { get; set; }
[Required]
public DateTime EntryDate { get; set; }
public bool AdStatus { get; set; }
[Required]
[Display(Name = "Category")]
public Category Category { get; set; }
}
And now I want to get the ID of the selected item:
public ActionResult Create(AdvertModel ad)
{
Advert nAD = new Advert();
nAD.Title = ad.Title;
nAD.Message = ad.Details;
nAD.PublishDate = ad.PubDate;
nAD.Category = ad.Category.ID;// here I always get null.
dc.Advert.AddObject(nAD);
dc.SaveChanges();
return View(ad);
}
Any idea where am I doing wrong??
The first parameter of The Html.DropDownList is the HTML Id.
Add a CategoryId to your ViewModel and change your Dropdown List to:
<%:Html.DropDownList("CategoryId", ViewData["Categories"] as SelectList, new { #class = "dropdown" })%>
Or this might work with your current code (but not tested):
<%:Html.DropDownList("Category_ID", ViewData["Categories"] as SelectList, new { #class = "dropdown" })%>

Resources