Working on a project in ASP.NET MVC 4, using Entity Framework Database first (Sql Server 2008). I have looked everywhere but I couldn't find any solution to this. I am faced with a situation where:
Cannot Create new or Update existing "Interns" The error message is :
DbUpdateException was unhandled by user code
I tried using try/catch exception but wasn't helpful.
The problem seems to come from the dropdown menus that I have. Not only the display box is not populated when in edit mode (when it has a value) but the data is not saved. It's not doing anything.
All free text fields are fine.
Here is the Controller:
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using InternApp.Models;
using System;
using System.Data.Entity.Infrastructure;
namespace InternApp.Controllers
{
public class InternController : Controller
{
private InternshipProgramEntities db = new InternshipProgramEntities();
//
// GET: /Intern/
public ActionResult Index()
{
var interns = db.Interns.Include(i => i.Department).Include(i => i.Intern_Coach).Include(i => i.Location).Include(i => i.Intern_Manager).Include(i => i.School).Include(i => i.Semester).Include(i => i.InternStatu);
return View(interns.ToList());
}
//
// GET: /Intern/Details/5
public ActionResult Details(int id = 0)
{
Intern intern = db.Interns.Find(id);
if (intern == null)
{
return HttpNotFound();
}
return View(intern);
}
//
// GET: /Intern/Create
public ActionResult Create()
{
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName");
ViewBag.CoachID = new SelectList(db.Intern_Coach.OrderBy(c => c.LastName), "InternCoachID", "CoachFullName");
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "BldgName");
ViewBag.ManagerID = new SelectList(db.Intern_Manager.OrderBy(m => m.LastName), "InternManagerID", "ManagerFullName");
ViewBag.SchoolID = new SelectList(db.Schools, "SchoolID", "SchoolName");
ViewBag.SemesterID = new SelectList(db.Semesters, "SemesterID", "SemesterName");
ViewBag.InternStatusID = new SelectList(db.InternStatus, "InternStatusID", "Status");
return View();
}
//
// POST: /Intern/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(
[Bind(Include = "InternID, InFirstName, InLastName, PersonalEmail, PersonalPhone, CHSEmail, CHSPhone, InternStatusID, LastStatusChangeDate, SchoolID, SemesterID, Major, PartTimeInterest, FTEAvailDate, GraduationDate, DepartmentID, TeamName, ManagerID, LocationID, ComputerNumber, ITInterests, InternStartDate, InternEndDate, PTStartDate, PTEndDate, FTEStartDate, FTEEndDate, InternSalary, PTSalary, FTESalary, ProgramFeedback, CoachID")]
Intern intern)
{
if (ModelState.IsValid)
{
try
{
db.Interns.Add(intern);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
}
}
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", intern.DepartmentID);
ViewBag.CoachID = new SelectList(db.Intern_Coach, "InternCoachID", "CoachFullName", intern.CoachID);
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "BldgName", intern.LocationID);
ViewBag.ManagerID = new SelectList(db.Intern_Manager, "InternManagerID", "ManagerFullName", intern.ManagerID);
ViewBag.SchoolID = new SelectList(db.Schools, "SchoolID", "SchoolName", intern.SchoolID);
ViewBag.SemesterID = new SelectList(db.Semesters, "SemesterID", "SemesterName", intern.SemesterID);
ViewBag.InternStatusID = new SelectList(db.InternStatus, "InternStatusID", "Status", intern.InternStatusID);
return View(intern);
}
//
// GET: /Intern/Edit/5
public ActionResult Edit(int id = 0)
{
Intern intern = db.Interns.Find(id);
if (intern == null)
{
return HttpNotFound();
}
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", intern.DepartmentID);
ViewBag.CoachID = new SelectList(db.Intern_Coach, "InternCoachID", "UserName", intern.CoachID);
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "BldgName", intern.LocationID);
ViewBag.ManagerID = new SelectList(db.Intern_Manager, "InternManagerID", "UserName", intern.ManagerID);
ViewBag.SchoolID = new SelectList(db.Schools, "SchoolID", "SchoolName", intern.SchoolID);
ViewBag.SemesterID = new SelectList(db.Semesters, "SemesterID", "SemesterName", intern.SemesterID);
ViewBag.InternStatusID = new SelectList(db.InternStatus, "InternStatusID", "Status", intern.InternStatusID);
return View(intern);
}
//
// POST: /Intern/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(
[Bind(Include = "InternID, InFirstName, InLastName, PersonalEmail, PersonalPhone, CHSEmail, CHSPhone, InternStatusID, LastStatusChangeDate, SchoolID, SemesterID, Major, PartTimeInterest, FTEAvailDate, GraduationDate, DepartmentID, TeamName, ManagerID, LocationID, ComputerNumber, ITInterests, InternStartDate, InternEndDate, PTStartDate, PTEndDate, FTEStartDate, FTEEndDate, InternSalary, PTSalary, FTESalary, ProgramFeedback, CoachID")]
Intern intern)
{
try
{
if (ModelState.IsValid)
{
db.Entry(intern).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DbUpdateException editEx)
{
}
ViewBag.DepartmentID = new SelectList(db.Departments, "DepartmentID", "DepartmentName", intern.DepartmentID);
ViewBag.CoachID = new SelectList(db.Intern_Coach, "InternCoachID", "UserName", intern.CoachID);
ViewBag.LocationID = new SelectList(db.Locations, "LocationID", "BldgName", intern.LocationID);
ViewBag.ManagerID = new SelectList(db.Intern_Manager, "InternManagerID", "UserName", intern.ManagerID);
ViewBag.SchoolID = new SelectList(db.Schools, "SchoolID", "SchoolName", intern.SchoolID);
ViewBag.SemesterID = new SelectList(db.Semesters, "SemesterID", "SemesterName", intern.SemesterID);
ViewBag.InternStatusID = new SelectList(db.InternStatus, "InternStatusID", "Status", intern.InternStatusID);
return View(intern);
}
Here is the Create View:
#model InternApp.Models.Intern
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
var u = new InternApp.Classes.Utilities();
}
<h2 style="margin-left:inherit">Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>New Intern</legend>
<div class="form-inline">
<div class="form-group" >
#* #Html.HiddenFor(model => model.InternID)*#
#Html.Label("First Name")
#Html.EditorFor(model => model.InFirstName)
#Html.ValidationMessageFor(model => model.InFirstName)
</div>
<div class="form-group">
#Html.LabelFor(model => model.InLastName)
#Html.EditorFor(model => model.InLastName)
#Html.ValidationMessageFor(model => model.InLastName)
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.PersonalEmail)
#Html.EditorFor(model => model.PersonalEmail)
#Html.ValidationMessageFor(model => model.PersonalEmail)
</div>
<div class="form-group">
#Html.LabelFor(model => model.PersonalPhone)
#Html.EditorFor(model => model.PersonalPhone)
#Html.ValidationMessageFor(model => model.PersonalPhone)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.CHSEmail)
#Html.EditorFor(model => model.CHSEmail)
#Html.ValidationMessageFor(model => model.CHSEmail)
</div>
<div class="form-group">
#Html.LabelFor(model => model.CHSPhone)
#Html.EditorFor(model => model.CHSPhone)
#Html.ValidationMessageFor(model => model.CHSPhone)
</div>
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.Hidden("InternStatusID")
#Html.Label("Status: ")
#* #Html.DropDownList("InternStatusID", String.Empty) *#
#Html.DropDownListFor(model => model.InternStatu.Status, new SelectList(u.StatusDropdown(), "Value", "Text"))
#Html.ValidationMessageFor(model => model.InternStatu.Status)
</div>
<div class="form-group">
#Html.Label("Last Status Change Date")
#Html.TextBoxFor(model => model.LastStatusChangeDate)
#Html.ValidationMessageFor(model => model.LastStatusChangeDate)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.Hidden("SchoolID")
#Html.Label("School")
#Html.DropDownListFor(model => model.School.SchoolName, new SelectList(u.SchoolDropdown(), "Value", "Text"))
#Html.ValidationMessageFor(model => model.School.SchoolName)
</div>
<div class="form-group">
#Html.LabelFor(model => model.SemesterID, "Semester")
#Html.DropDownList("SemesterID", String.Empty)
#Html.ValidationMessageFor(model => model.SemesterID)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.Major)
#Html.EditorFor(model => model.Major)
#Html.ValidationMessageFor(model => model.Major)
</div>
<div class="form-group">
#Html.LabelFor(model => model.PartTimeInterest)
#Html.EditorFor(model => model.PartTimeInterest)
#Html.ValidationMessageFor(model => model.PartTimeInterest)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.FTEAvailDate)
#Html.TextBoxFor(model => model.FTEAvailDate)
#Html.ValidationMessageFor(model => model.FTEAvailDate)
</div>
<div class="form-group">
#Html.LabelFor(model => model.GraduationDate)
#Html.TextBoxFor(model => model.GraduationDate)
#Html.ValidationMessageFor(model => model.GraduationDate)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.HiddenFor(model => model.DepartmentID)
#Html.Label("Department")
#Html.DropDownList("DepartmentID", String.Empty)
</div>
<div class="form-group">
#Html.LabelFor(model => model.TeamName)
#Html.EditorFor(model => model.TeamName)
#Html.ValidationMessageFor(model => model.TeamName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ManagerID, "Intern_Manager")
#Html.DropDownList("ManagerID", String.Empty)
#Html.ValidationMessageFor(model => model.ManagerID)
</div>
<div class="form-group">
#Html.LabelFor(model => model.LocationID, "Location")
#Html.DropDownList("LocationID", String.Empty)
#Html.ValidationMessageFor(model => model.LocationID)
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.ComputerNumber)
#Html.EditorFor(model => model.ComputerNumber)
#Html.ValidationMessageFor(model => model.ComputerNumber)
</div>
<div class="form-group">
#Html.LabelFor(model => model.ITInterests)
#Html.EditorFor(model => model.ITInterests)
#Html.ValidationMessageFor(model => model.ITInterests)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.InternStartDate)
#Html.TextBoxFor(model => model.InternStartDate)
#Html.ValidationMessageFor(model => model.InternStartDate)
</div>
<div class="form-group">
#Html.LabelFor(model => model.InternEndDate)
#Html.TextBoxFor(model => model.InternEndDate)
#Html.ValidationMessageFor(model => model.InternEndDate)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.PTStartDate)
#Html.TextBoxFor(model => model.PTStartDate)
#Html.ValidationMessageFor(model => model.PTStartDate)
</div>
<div class="form-group">
#Html.LabelFor(model => model.PTEndDate)
#Html.TextBoxFor(model => model.PTEndDate)
#Html.ValidationMessageFor(model => model.PTEndDate)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.FTEStartDate)
#Html.TextBoxFor(model => model.FTEStartDate)
#Html.ValidationMessageFor(model => model.FTEStartDate)
</div>
<div class="form-group">
#Html.LabelFor(model => model.FTEEndDate)
#Html.TextBoxFor(model => model.FTEEndDate)
#Html.ValidationMessageFor(model => model.FTEEndDate)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.InternSalary)
#Html.EditorFor(model => model.InternSalary)
#Html.ValidationMessageFor(model => model.InternSalary)
</div>
<div class="form-group">
#Html.LabelFor(model => model.PTSalary)
#Html.EditorFor(model => model.PTSalary)
#Html.ValidationMessageFor(model => model.PTSalary)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.FTESalary)
#Html.EditorFor(model => model.FTESalary)
#Html.ValidationMessageFor(model => model.FTESalary)
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProgramFeedback)
#Html.EditorFor(model => model.ProgramFeedback)
#Html.ValidationMessageFor(model => model.ProgramFeedback)
</div>
</div>
<div class="form-inline">
<div class="form-group">
#Html.LabelFor(model => model.CoachID, "Intern_Coach")
#Html.DropDownList("CoachID", String.Empty)
#Html.ValidationMessageFor(model => model.CoachID)
</div>
</div>
<div id="fUpload">
#Html.Label("Attach a File")
<input type="file" name="fileUpload" id="fileUpload" />
</div>
<br />
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div style="margin-left:inherit" >
#Html.ActionLink("Back to List", "Index")
</div>
And the Model:
namespace InternApp.Models
{
using System;
using System.Collections.Generic;
public partial class Intern
{
public int InternID { get; set; }
public string InFirstName { get; set; }
public string InLastName { get; set; }
public string InternFullName { get { return InFirstName + " " + InLastName; } }
public string PersonalEmail { get; set; }
public string PersonalPhone { get; set; }
public string CHSEmail { get; set; }
public string CHSPhone { get; set; }
public int InternStatusID { get; set; }
public System.DateTime LastStatusChangeDate { get; set; }
public int SchoolID { get; set; }
public Nullable<int> SemesterID { get; set; }
public string Major { get; set; }
public Nullable<bool> PartTimeInterest { get; set; }
public Nullable<System.DateTime> FTEAvailDate { get; set; }
public Nullable<System.DateTime> GraduationDate { get; set; }
public Nullable<int> DepartmentID { get; set; }
public string TeamName { get; set; }
public Nullable<int> ManagerID { get; set; }
public Nullable<int> LocationID { get; set; }
public string ComputerNumber { get; set; }
public string ITInterests { get; set; }
public Nullable<System.DateTime> InternStartDate { get; set; }
public Nullable<System.DateTime> InternEndDate { get; set; }
public Nullable<System.DateTime> PTStartDate { get; set; }
public Nullable<System.DateTime> PTEndDate { get; set; }
public Nullable<System.DateTime> FTEStartDate { get; set; }
public Nullable<System.DateTime> FTEEndDate { get; set; }
public Nullable<decimal> InternSalary { get; set; }
public Nullable<decimal> PTSalary { get; set; }
public Nullable<decimal> FTESalary { get; set; }
public string ProgramFeedback { get; set; }
public Nullable<int> CoachID { get; set; }
public virtual Department Department { get; set; }
public virtual Intern_Coach Intern_Coach { get; set; }
public virtual Location Location { get; set; }
public virtual Intern_Manager Intern_Manager { get; set; }
public virtual School School { get; set; }
public virtual Semester Semester { get; set; }
public virtual InternStatu InternStatu { get; set; }
public virtual Intern Intern1 { get; set; }
public virtual Intern Intern2 { get; set; }
}
}
I have created a strongly typed view using visual studio and have added some dropdownlists for the user to select an option from a connected database table column but these dropdownlists seem to cause some issues. I keep getting the errors below and I am not sure why. These drop downs should be saving the options as a string to corresponding item record. Not sure why it is looking for a key named AssignedTo. Any suggestions? All help is much appreciated.
Error Message:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'AssignedTo'.
Source Error:
Line 34: </div>
Line 35: <div class="editor-field">
Line 36: #Html.DropDownListFor(model => model.AssignedTo, (SelectList)ViewBag.AssignedToList)
Line 37: #Html.ValidationMessageFor(model => model.AssignedTo)
Line 38: </div>
Here is my strongly typed Create View:
#model ApIssues.Models.AP_Tasks
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Issue</legend>
<div class="editor-label">
#Html.LabelFor(model => model.TaskDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TaskDate)
#Html.ValidationMessageFor(model => model.TaskDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.InvDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.InvDate)
#Html.ValidationMessageFor(model => model.InvDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AssignedTo)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.AssignedTo, (SelectList)ViewBag.AssignedToList)
#Html.ValidationMessageFor(model => model.AssignedTo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CC)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.CC, (SelectList)ViewBag.CcToList)
#Html.ValidationMessageFor(model => model.CC)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Whse)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Whse, (SelectList)ViewBag.WarehouseList)
#Html.ValidationMessageFor(model => model.Whse)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PO)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PO)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FreightNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FreightNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VendName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.VendName)
#Html.ValidationMessageFor(model => model.VendName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ReqCompDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ReqCompDate)
#Html.ValidationMessageFor(model => model.ReqCompDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TaskType)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TaskType)
#Html.ValidationMessageFor(model => model.TaskType)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Here is my model:
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Validation;
namespace ApIssues.Models
{
using System;
using System.Collections.Generic;
public partial class AP_Tasks
{
[Required]
public int TaskID { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Task Date")]
public Nullable<System.DateTime> TaskDate { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Task Type")]
public string TaskType { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Assigned By")]
public string AssignedBy { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Assigned To")]
public string AssignedTo { get; set; }
[DataType(DataType.Text)]
[Display(Name = "CC")]
public string CC { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Warehouse")]
public string Whse { get; set; }
[DataType(DataType.Text)]
[Display(Name = "PO #")]
public string PO { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Freight #")]
public string FreightNo { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Vendor Name")]
public string VendName { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Req. Complete Date")]
public Nullable<System.DateTime> ReqCompDate { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Due Date")]
public Nullable<System.DateTime> DueDate { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Completion Date")]
public Nullable<System.DateTime> CompDate { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Notes Summary")]
public string Notes { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Invoice Date")]
public Nullable<System.DateTime> InvDate { get; set; }
[Display(Name = "Company Number")]
public Nullable<int> CoNo { get; set; }
[Display(Name = "Note Count")]
public Nullable<int> NoteCnt { get; set; }
}
}
Here is my Action:
[HttpGet]
public ActionResult Create()
{
//TODO: Add drop down lists
//TODO: Change the Cono in Query1
var nxtDb = new nxtSQLEntities();
var whses = from w in nxtDb.icsds select w.whse;
var warehouseList = new SelectList(whses);
ViewBag.WarehouseList =
warehouseList;
var userDb = new PDDAEntities1();
var query1 = from u in userDb.Users where u.Cono == 1 select new {u.UserName, u.FirstName, u.LastName};
var query2 = from gm in userDb.GroupMembers
join ug in userDb.UserGroups on gm.GroupID equals ug.GroupID
join u in userDb.Users on gm.UserName equals u.UserName
where ug.GroupName == "AP Department" || ug.GroupName == "MIS"
orderby new {u.LastName, u.FirstName}
select new {UserName = u.UserName, FirstName = u.FirstName, LastName = u.LastName};
var query3 = query1.Concat(query2);
var results = new List<string>{};
results.AddRange(query3.Select(entry => entry.UserName));
ViewBag.AssignedToList = new SelectList(results);
ViewBag.CcToList = new SelectList(results);
return View();
}
[HttpPost]
public ActionResult Create(AP_Tasks task)
{
// Save an task to the database
var db = new Accounting_AaronTestEntities();
try
{
db.AP_Tasks.Add(task);
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
return View();
}
return RedirectToAction("Index");
}
Anyone know why I am getting this error?
Try it this way.
#Html.DropDownListFor(model => model.AssignedTo,
new SelectList(ViewBag.AssignedToList, "Id", "AssignedTo"), "---Select Assigner---", new { ID = "ddlAssigned" })
Hope it helps.
try variants of the top two answers here:
Having difficulty using an ASP.NET MVC ViewBag and DropDownListfor
I'm trying to get a dropdown menu along side my other text inputs, I've been tracking a music store tutorial for this specific feature, but I cant seem to get mine to work. I've been revising my code and comparing for hours but I cant see my errors, If anyone can help it would be greatly appreciated.
Here is my controller code:
// GET: /Default1/Create
public ActionResult Create()
{
ViewBag.CardTypeId = new SelectList(db.CardTypee, "CardTypeId", "Type");
return View();
}
//
// POST: /Default1/Create
[HttpPost]
public ActionResult Create(Card card)
{
if (ModelState.IsValid)
{
db.Cards.Add(card);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CardTypeId = new SelectList(db.CardTypee, "CardTypeId", "Type", card.CardTypeId);
return View(card);
}
My models that I have:
Card.cs
namespace ActualPayment.Models
{
public class Card
{
public int Id { get; set; }
public CardType CardType { get; set; }
public int CardTypeId { get; set; }
public string Name { get; set; }
public string CardNumber { get; set; }
public int SortCode { get; set; }
public int SecurityCode { get; set; }
public int ExpirationDate { get; set; }
}
}
CardType.cs
namespace ActualPayment.Models
{
public partial class CardType
{
[Key] public int CardTypeId { get; set; }
public string Type { get; set; }
}
}
CardTypes.cs
namespace ActualPayment.Models
{
public class CardTypes : DropCreateDatabaseIfModelChanges<CardPayment>
{
protected override void Seed(CardPayment context)
{
var cardType = new List<CardType>
{
new CardType { Type = "Visa/Delta/Electron" },
new CardType { Type = "Master Card/Euro Card" },
new CardType { Type = "American Express" },
new CardType { Type = "Solo/Maestro" },
new CardType { Type = "Maestro" },
};
}
}
}
CardPayments.cs
namespace ActualPayment.Models
{
public class CardPayment : DbContext
{
public DbSet<CardType> CardTypee { get; set; }
public DbSet<Card> Cards { get; set; }
}
}
And my view:
#model ActualPayment.Models.Card
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Card</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CardTypeId, "CardType")
</div>
<div class="editor-field">
#Html.DropDownList("CardTypeId", String.Empty)
#Html.ValidationMessageFor(model => model.CardTypeId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CardNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CardNumber)
#Html.ValidationMessageFor(model => model.CardNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SortCode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SortCode)
#Html.ValidationMessageFor(model => model.SortCode)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SecurityCode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SecurityCode)
#Html.ValidationMessageFor(model => model.SecurityCode)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ExpirationDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ExpirationDate)
#Html.ValidationMessageFor(model => model.ExpirationDate)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Seems like there's nothing wrong with the code.
Chrome capture for posted values
value at action
Did you mean the CardTypeId is not getting populated??
I have a Userstats model, and a user model, the Modelstate.isvalid in the controller is returning false, I think it may have something to do with the reltionship between the the two models but i'm not sure
userstats model:
public class UserStats
{
Calculator CalculateStats = new Calculator();
public ActivityLevel ActivitySelected { get;set; }
[Key]
public int ID { get; set; }
public User User { get; set; }
[DisplayName("Weight")]
[Required]
public double Weight { get; set; }
[DisplayName("Chest Measurement")]
[Required]
public double ChestMeasurement { get; set; }
[DisplayName("Hip Measurement")]
[Required]
public double HipMeasurement { get; set; }
[DisplayName("Waist Measurement")]
[Required]
public double WaistMeasurement { get; set; }
[DisplayName("Bicep Measurement")]
[Required]
public double BicepMeasurment { get; set; }
[DisplayName("Height Measurement(Inches)")]
[Required]
public double Height { get; set; }
[DisplayName("Body Fat %")]
[NotMapped]
public double BodyFat { get; set; }
[NotMapped]
public double BMI
{
get { return CalculateStats.CalculateBMI(Weight,Height); }
}
[NotMapped]
public double BMR
{
//get { return CalculateStats.CalculateBMR(user.SelectedGender, Weight, Height, user.Age); }
get { return 0; }
}
[DisplayName("Stats Log Date")]
[Required]
public DateTime StatDate { get; set; }
[DisplayName("Target Weight")]
[Required]
public double TargetWeight { get; set; }
[DisplayName("Target Date")]
[Required]
public DateTime TargetDate { get; set; }
[DisplayName("Wrist Measurement(Inches)")]
[Required]
public double WristMeasurement { get; set; }
[DisplayName("Forearm Measurement(Inches)")]
[Required]
public double ForeArm { get; set; }
[DisplayName("Daily Caloric Intake")]
[NotMapped]
public double DailyIntake { get; set; }
[DisplayName("Daily Allowance")]
[NotMapped]
public double DailyCalories { get; set; }
[DisplayName("Lean Body Mass")]
[NotMapped]
public double LeanMass { get; set; }
}
user model:
public class User
{
[Key]
public int ID { get; set; }
public virtual ICollection<UserStats> UserStats { get; set; }
[DisplayName("First Name")]
[Required]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[Required]
public string LastName { get; set; }
[DisplayName("D.O.B")]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
private int _age;
[NotMapped]
public int Age
{
get { return _age; }
set
{
DateTime today = DateTime.Today;
_age = today.Year - DOB.Year;
if (DOB > today.AddYears(-_age)) _age--;
}
}
[DisplayName("Address")]
public string Address { get; set; }
[Required]
public string Email { get; set; }
[Required]
public Gender Gender { get; set; }
[DisplayName("UserName")]
public string UserName { get; set; }
public Gender SelectedGender { get; set; }
}
}
registeMale controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RegisterMale(User u,UserStats userstats)
{
if (ModelState.IsValid)
{
var user = db.Users.SingleOrDefault(i => i.ID == u.ID);
userstats.User = user;
db.UserStats.Add(userstats);
db.SaveChanges();
return RedirectToAction("Details", "Dashboard", new { id = userstats.ID });
}
return View(userstats);
}
View:
<fieldset>
<legend>UserStats</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Weight)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Weight)
#Html.ValidationMessageFor(model => model.Weight)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ChestMeasurement)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ChestMeasurement)
#Html.ValidationMessageFor(model => model.ChestMeasurement)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HipMeasurement)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HipMeasurement)
#Html.ValidationMessageFor(model => model.HipMeasurement)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.WaistMeasurement)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.WaistMeasurement)
#Html.ValidationMessageFor(model => model.WaistMeasurement)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.BicepMeasurment)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BicepMeasurment)
#Html.ValidationMessageFor(model => model.BicepMeasurment)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Height)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Height)
#Html.ValidationMessageFor(model => model.Height)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StatDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StatDate)
#Html.ValidationMessageFor(model => model.StatDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TargetWeight)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TargetWeight)
#Html.ValidationMessageFor(model => model.TargetWeight)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TargetDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TargetDate)
#Html.ValidationMessageFor(model => model.TargetDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.WristMeasurement)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.WristMeasurement)
#Html.ValidationMessageFor(model => model.WristMeasurement)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ForeArm)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ForeArm)
#Html.ValidationMessageFor(model => model.ForeArm)
</div>
<table>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.Sedentary) Sedentary
</td>
</tr>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.LightActivity) Light Activity
</td>
</tr>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.Moderate) Moderate
</td>
</tr>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.Active) Active
</td>
</tr>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.Extra) Extra
</td>
</tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
It seems your models are not connected. There is no same id filed. You may add userID to UserStats. And I think your RegisterMale method expects only one model UserStats. Just rewrite it as follows
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RegisterMale(UserStats model)
{
if (ModelState.IsValid)
{
var user = db.Users.SingleOrDefault(i => i.ID == model.userID );
db.UserStats.Add(userstats);
db.SaveChanges();
return RedirectToAction("Details", "Dashboard", new { id = userstats.ID });
}
return View(userstats);
}
How to get the data from the file fields?
My class Movie:
public class Movie
{
public int ID { get; set; }
[Display(Name = "Movie Title")]
[Required(ErrorMessage = "The Title Field Is Required.")]
public string Title { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
[Display(Name = "Release Date")]
public DateTime ReleaseDate { get; set; }
[Required(ErrorMessage = "The Genere Field Is Required.")]
public string Genre { get; set; }
[DisplayFormat(DataFormatString = "{0:F3}")]
public decimal Price { get; set; }
public List<Image> Images = new List<Image>();
public List<File> Files = new List<File>();
public List<Link> Links = new List<Link>();
public Movie()
{
ID = 0;
Price = 0;
Title = "movie";
Genre = "דרמה";
ReleaseDate = DateTime.Now;
var image1 = new Image
{
ID = 0,
FileName = ""
};
var image2 = new Image
{
ID = 0,
FileName = ""
};
var image3 = new Image
{
ID = 0,
FileName = ""
};
Images.Add(image1);
Images.Add(image2);
Images.Add(image3);
}
}
I have an editor template for Image:
#model BermanCRM.Models.Image
<div class="fl">
<h3>
Image</h3>
<p>
#Html.LabelFor(x => x.FileName)
#Html.TextBoxFor(x => x.FileName, new { type = "file" })
</p>
<p>
#Html.LabelFor(x => x.Order)
#Html.EditorFor(x => x.Order)
</p>
</div>
My movie create view:
#model BermanCRM.Models.Movie
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Movies", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Movie</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Title)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Title)
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ReleaseDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ReleaseDate)
#Html.ValidationMessageFor(model => model.ReleaseDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Genre)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Genre, new SelectList(#ViewBag.Generelist, "Text", "Value"), "--select--")
#Html.ValidationMessageFor(model => model.Genre)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
<h2>Images</h2>
#Html.EditorFor(model => model.Images)
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
My Controller:
public ActionResult Create()
{
ViewBag.Generelist = listGeners;
return View(new Movie());
}
//
// POST: /Movies/Create
[HttpPost]
public ActionResult Create(Movie movie, IEnumerable<HttpPostedFileBase> files)
{
try
{
movie.Insert();
foreach (HttpPostedFileBase file in files)
{
file.SaveAs(Path.Combine(Server.MapPath("~/Upload"), Path.GetFileName(file.FileName)));
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
By looking your code the Action Result HttpPostedFileBase declaration name "files" and File upload control name is not same.
<input id="files" type="file" name="files" />
IEnumerable<HttpPostedFileBase> files
name="files" and HttpPostedFileBase files Must be same...
Keep the same name.. it will work.,