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" })%>
Related
In my ASP.NET MVC application, I have a form with drop-down list. If the user did not select a category and submitted the form, I will get exception. So How do I send validation error from the controller to the view? because I don't want to write JavaScript.
This is the drop-down list:
#Html.DropDownListFor(m => m.Article.CategoryId, new SelectList(Model.Categories, "Id", "Name"), "Select Category", new { #class = "form-control" })
I know this way is working but I need that label (Select Category)
#Html.DropDownListFor(m => m.Article.CategoryId, new SelectList(Model.Categories, "Id", "Name"), null, new { #class = "form-control" })
All and New controllers:
[HttpPost]
public ActionResult New(Article article)
{
if(ModelState.IsValid)
{
string FullName = HttpContext.GetOwinContext()
.GetUserManager<ApplicationUserManager>()
.FindById(User.Identity.GetUserId()).FullName;
article.AuthorName = FullName;
article.UserId = User.Identity.GetUserId();
db.Aricles.Add(article);
db.SaveChanges();
return RedirectToAction("All");
}
}
public ActionResult All()
{
var Articles = db.Aricles.ToList();
return View(Articles);
}
My model:
public class Article
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Body { get; set; }
public string UserId { get; set; }
public string AuthorName { get; set; }
public ApplicationUser User { get; set; }
public Category Category { get; set; }
public int CategoryId { get; set; }
}
I tried to use [Required] attribute but I don't know why it does not work.
This is a screenshot of the exception click
I found the issue after I thought about the comment written by Mannan Bahelim . I don't get validation error because the model in the view was ArticleCategoryViewModel while it should be Article model.
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" })
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.
I'm new to MVC and are having a hard time figuring some "basic" things out.
I have a ViewModel shaped as follows:
public class ProjectViewModel
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
[Required]
[Display(Name = "Final due date")]
public DateTime FinalDueDate { get; set; }
[Required]
[Display(Name = "Attached equipment")]
public Equipment AttachedEquipment { get; set; }
}
In my Create view I would like to be able to select the value for AttachedEquipment from a dropdownlist. I have a table in my database with all the available Equipments.
I know there is an #Html helper #Html.DropDownListFor which serves this very purpose. However I fail to see how I get the values from the database and spit them out into my view.
My ProjectController looks like this:
private AdventureWorks db = new AdventureWorks();
// GET: Project
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult Create()
{
// I'm guessing this is where I need to do some magic
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProjectViewModel model)
{
if (ModelState.IsValid)
{
var project = new Project
{
Title = model.Title,
Description = model.Description,
CreatedDate = DateTime.Now,
FinalDueDate = model.FinalDueDate,
Equipment = model.Equipment
};
db.Projects.Add(project);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
How do I load the Equipment values from my DB into a dropdownlist in my Create view?
Since you cant bind a dropdownlist to the complex object AttachedEquipment, I would change the view model to include properties for the selected equipment and a SelectList for the options
public class ProjectViewModel
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
[Required]
[Display(Name = "Final due date")]
public DateTime FinalDueDate { get; set; }
[Required(ErrorMessage="Please select equipment)]
public int? SelectedEquipment { get; set; }
public SelectList EquipmentList { get; set; }
}
Controller
public ActionResult Create()
{
ProjectViewModel model = new ProjectViewModel();
// Assumes your Equipments class has properties ID and Name
model.EquipmentList = new SelectList(db.Equipments, "ID", "Name");
return View(model);
}
View
#model ProjectViewModel
#using(Html.BeginForm())
{
....
#Html.DropDownListFor(m => m.SelectedEquipment, Model.EquipmentList, "--Please select--")
....
}
Alternatively you can bind to m => m.AttachedEquipment.ID (assuming Equipment contains property ID)
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"})