The code will not save the value to the Musician Entity.
I'm using a ViewBag that is saving a SelectList and it displays the content from the database but on save it is null for the musician.PrimaryInstrument field when debugging.
Razor :
<td>
#Html.LabelFor(model => model.PrimaryInstrument, htmlAttributes: new { #class = "control-label col-md-2" })
</td>
<td>
#Html.DropDownList("InstrumentList")
</td>
Controller:
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Musician musician = (Musician)db.Contractor.Find(id);
if (musician == null)
{
return HttpNotFound();
}
ViewBag.InstrumentList = new SelectList(db.Instrument, "ID", "Name");
return View(musician);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Musician musician, HttpPostedFileBase image)
{
if(ModelState.IsValid)
{
if (image != null)
{
UploadImage(musician, image);
}
musician.YearsOfExperience = Convert.ToInt16(Request["yearsOfExperience"]);
musician.CreateDate = DateTime.Now;
musician.NextDateAvailable = DateTime.Now;
db.Entry(musician).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Profile");
}
return View();
}
Instrument Model:
public class Instrument
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<Musician> Musician { get; set; }
}
}
Musician Model:
public class Musician : Contractor
{
[Display(Name="Primary Instrument")]
public string PrimaryInstrument { get; set; }
[Display(Name = "Primary Genre")]
public string PrimaryGenre { get; set; }
[Display(Name = "Website Link")]
public string WebsiteLink { get; set; }
[Display(Name = "Youtube Link")]
public string YouTubeLink { get; set; }
[Display(Name = "SoundCloud Link")]
public string SoundCloudLink { get; set; }
[Display(Name = "ReverbNation Link")]
public string ReverbNationLink { get; set; }
public ICollection<Instrument> Instruments { get; set; }
}
Your not currently binding the selected instrument to the property PrimaryInstrument. Your helper should be
#Html.DropDownListFor(m => m.PrimaryInstrument, (SelectList)ViewBag.InstrumentList)
Note this will bind the ID property of Instrument to the property PrimaryInstrument
Note also that if ModelState is not valid, you also need to reassign the ViewBag.InstrumentList property - ViewBag.InstrumentList = new SelectList(db.Instrument, "ID", "Name"); before you call return View(musician);
Related
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();
}
I have the following problem when displaying list of personal file,
but I used the (using System.Data.Entity) and (Include) in the query it's not working
Class Model
public class PersonalFile
{
public int Id { get; set; }
[StringLength(50)]
public string FileName { get; set; }
[StringLength(500)]
public string FilePath { get; set; }
public DateTime UploadDateTime { get; set; }
public int EmployeeId { get; set; }
[ForeignKey("EmployeeId")]
public Employee Employee { get; set; }
public int? FileCategoryId { get; set; }
[ForeignKey("FileCategoryId")]
public virtual FileCategory FileCategory { get; set; }
}
Class View Model
public class PersonalFileViewModel
{
public int Id { get; set; }
[StringLength(50)]
public string FileName { get; set; }
[StringLength(500)]
public string FilePath { get; set; }
public int EmployeeId { get; set; }
[Required]
public int FileCategoryId { get; set; }
public IEnumerable<PersonalFile> PersonalFiles { get; set; }
}
Class Model File Category
public class FileCategory
{
public int FileCategoryId { get; set; }
public string categoryName { get; set; }
public string optionGroup { get; set; }
public virtual ICollection<PersonalFile> PersonalFile { get; set; }
}
Action Method
public ActionResult Index(int? id)
{
if (id == null)
return HttpNotFound();
var empl = _dbContext.Employees.SingleOrDefault(c => c.EmployeeId == id);
if (empl == null)
return HttpNotFound();
ViewBag.FileCategoryId = new SelectList(_dbContext.FileCategory, "FileCategoryId", "categoryName" , "optionGroup", 0);
var vwModel = new PersonalFileViewModel
{
EmployeeId = empl.EmployeeId,
PersonalFiles = _dbContext.PersonalFiles.Include(p => p.Employee).Include(p => p.FileCategory).Where(x => x.EmployeeId == id)
};
NameAndImage(empl.EmployeeId);
return View(vwModel);
}
View
foreach (var j in Model.PersonalFiles)
{
<tr style="border-top: 1px solid black;">
<td style="vertical-align: middle;">#j.FileName</td>
<td style="vertical-align: middle;"> #j.FileCategory.categoryName </td>
<td style="vertical-align: middle;">#j.UploadDateTime</td>
<td>
Download
#Html.ActionLink("Delete", "Delete", new { j.Id }, new { #class = "btn btn-danger btn-sm", onclick = "return confirm('Do you really want to delete this file?');" })
</td>
</tr>
}
enter image description here
Firstly, make sure that with each PersonalFile belongs to FileCategory accordingly.
Secondly, You should .ToList() to force our query to execute immediately instead.
PersonalFiles = _dbContext.PersonalFiles.Include(p => p.Employee).Include(p => p.FileCategory).Where(x => x.EmployeeId == id).ToList()
I solved the problem by putting this line Code on the View
#(j.FileCategory == null ? "" : j.FileCategory.categoryName)
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 creating new product belonging to the category model.When i execute my Create method, the error invoke that
"Object Reference not set to instance of object" on "model" object
My Controller class:
public ActionResult CreateProduct()
{
SetCateProductViewBag();
return View(new CateProdViewModel());
}
[HttpPost]
public ActionResult CreateProduct(CateProdViewModel model)
{
var ValidImageTypes = new String[]
{
"image/gif",
"image/jpeg",
"image/jpg",
"image/pjpeg",
"image/png"
};
if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0)
{
ModelState.AddModelError("ImageUpload", "This Field is required.");
}
else if (!ValidImageTypes.Contains(model.ImageUpload.ContentType))
{
ModelState.AddModelError("ImageUload", "Please choose either a GIF,jpg or png type of file.");
}
if (ModelState.IsValid)
{
var prod = new Product
{
// CategoryName =model.category.CategoryName,
//CategoryDescription=model.category.CategoryDescription,
//CategoryId=model.CategoryId,
ProductName = model.ProductName,
ProductDescription = model.ProductDescription,
Model = model.Model,
ProductPrice = model.ProductPrice,
AvailableForSale = model.AvailableForSale,
Shippable = model.Shippable,
AvailableStock = model.AvailableStock,
ProductPicture = model.ProductPicture
};
SetCateProductViewBag(prod.CategoryId);
if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
{
var UploadDir = "~/Uploads";
var ImagePath = Path.Combine(Server.MapPath(UploadDir), model.ImageUpload.FileName);
var ImageUrl = Path.Combine(UploadDir, model.ImageUpload.FileName);
model.ImageUpload.SaveAs(ImagePath);
prod.ProductPicture = ImageUrl;
}
productContext.product.Add(prod);
productContext.SaveChanges();
return RedirectToAction("CategoryIndex");
}
return View(model);
}
CateProdViewModel class:
public class CateProdViewModel
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string CategoryDescription { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public int AvailableStock { get; set; }
public decimal ProductPrice { get; set; }
public string Model { get; set; }
public bool AvailableForSale { get; set; }
public bool Shippable { get; set; }
[DataType(DataType.ImageUrl)]
public string ProductPicture { get; set; }
public int SelectedValue { get; set; }
[DataType(DataType.Upload)]
public HttpPostedFileBase ImageUpload { get; set; }
public virtual Category category { get; set; }
[Display(Name="Product Categories")]
public virtual ICollection<Category> categories { get; set; }
}
Entity classes for Category and Product:
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public int AvailableStock { get; set; }
public decimal ProductPrice { get; set; }
public string Model { get; set; }
public bool AvailableForSale { get; set; }
public bool Shippable { get; set; }
public string ProductPicture { get; set; }
public int CustomerId { get; set; }
public int CategoryId { get; set; }
public virtual Category category { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public string CategoryDescription { get; set; }
public virtual ICollection<Product> product { get; set; }
}
My View:
#model SmartShoppingCart.Models.CateProdViewModel
#{
ViewBag.Title = "CreateProduct";
}
<h2>Create Product</h2>
<form action="" method="post" enctype="multipart/form-data">
<div>
#Html.LabelFor(m=>m.CategoryId,"Category")
#Html.DropDownList("CategoryId",ViewBag.categories as SelectList, string.Empty)
#Html.ValidationMessageFor(m=>m.CategoryId)
</div>
<div>
#Html.HiddenFor(m=>m.CategoryId)
</div>
<div>
#Html.LabelFor(m=>m.ProductName)
#Html.TextBoxFor(m=>m.ProductName)
#Html.ValidationMessageFor(m=>m.ProductName)
</div>
<div>
#Html.LabelFor(m=>m.ProductDescription)
#Html.TextBoxFor(m=>m.ProductDescription)
#Html.ValidationMessageFor(m=>m.ProductDescription)
</div>
<div>
#Html.LabelFor(m=>m.Model)
#Html.TextBoxFor(m=>m.Model)
#Html.ValidationMessageFor(m=>m.Model)
</div>
<div>
#Html.LabelFor(m=>m.ProductPrice)
#Html.TextBoxFor(m=>m.ProductPrice)
#Html.ValidationMessageFor(m=>m.ProductPrice)
</div>
<div>
#Html.LabelFor(m=>m.AvailableForSale)
#Html.TextBoxFor(m=>m.AvailableForSale)
#Html.ValidationMessageFor(m=>m.AvailableForSale)
</div>
<div>
#Html.LabelFor(m=>m.Shippable)
#Html.TextBoxFor(m=>m.Shippable)
#Html.ValidationMessageFor(m=>m.Shippable)
</div>
<div>
#Html.LabelFor(m=>m.AvailableStock)
#Html.TextBoxFor(m=>m.AvailableStock)
#Html.ValidationMessageFor(m=>m.AvailableStock)
</div>
<div>
#Html.LabelFor(m=>m.ImageUpload)
#Html.TextBoxFor(m => m.ImageUpload, new {type="file" })
</div>
<div>
<button type="submit" value="Add" ></button>
</div>
</form>
private void SetCateProductViewBag(int? CateId = null)
{
if (CateId == null)
{
ViewBag.Categories = new SelectList(productContext.category, "CategoryId", "CategoryName");
}
else
{
ViewBag.Categories = new SelectList(productContext.category.ToArray(),"CategoryId","CategoryName",CateId);
}
}
Your error occurs because your model is null on post back. The model is null because it contains a property named Model and the parameter name of the action method is also named model which is confusing the poor DefaultModelBinder. Either change the name of the property to something else or change the parameter name in your post action method to something else.
Why don't you change the first action to:
public ActionResult CreateProduct(CateProdViewModel model)
{
SetCateProductViewBag();
return View(model);
}
And your DefaultModelBinder will instantiate the model so it's never null.
Other than that, I need to know what you mean by saying When i execute my Create method. Since you don't have a Create method there. You have CreateProduct and you got 2 of them. Is this a POST or GET request?
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"})