Cannot create or update values in mvc entity framework - c#
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; }
}
}
Related
How to add validation Rule for dynamically created multiple input in ASP.net?
Account Model Class: [Table("Accounts")] public class Account { public int Id { get; set; } public string CompanyName { get; set; } public float Interval { get; set; } } Mobile Model Class: public class Mobile { public int Id { get; set; } public string MobileNo { get; set; } public virtual Account Account { get; set; } public static Mobile Add(string mobile) { Mobile mobiles = new Mobile(); mobiles.MobileNo = mobile; return mobiles; } } Thus an account can have multiple mobile numbers. Now I create a form where multiple mobile numbers can be inserted: #model PowerSupply.Models.CompanyAccountViewModel #{ ViewBag.Title = "Register"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h3>Register</h3> <br /> #using (Html.BeginForm()) { #Html.AntiForgeryToken() #Html.ValidationSummary(true, "", new { #class = "text-danger" }) <div class="form-group row"> #Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "col-sm-2 col-md-1 col-form-label" }) <div class="col-sm-10 col-md-3"> #Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } }) #Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" }) </div> </div> <div class="form-group row"> #Html.LabelFor(model => model.Interval, htmlAttributes: new { #class = "col-sm-2 col-md-1 col-form-label" }) <div class="col-sm-10 col-md-3"> #Html.EditorFor(model => model.Interval, new { htmlAttributes = new { #class = "form-control" } }) #Html.ValidationMessageFor(model => model.Interval, "", new { #class = "text-danger" }) </div> </div> <div class="form-group row"> #Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "col-sm-2 col-md-1 col-form-label" }) <div class="col-sm-10 col-md-3"> <span class="add-new-icon glyphicon glyphicon-plus-sign" id="add_mobile"> </span> <input name="Mobile" class="form-control" id="mobile_no" /> </div> </div> <div class="form-group row new_mobile_wrapper"> <div class="col-md-offset-3"> <div class="new_mobile_container"> </div> </div> </div> <div class="form-group row"> <div class="col-md-offset-2 col-sm-10 col-md-2"> <input type="submit" value="Register" class="btn btn-primary col-sm-offset-1" /> </div> </div> } the form look likes: And Finally I set validation as follows: public CompanyAccountViewModel Handle(CompanyAccountRegistrationResponseMessage message, CompanyAccountViewModel viewModel, ModelStateDictionary modelState) { if(!message.ValidationResult.IsValid) { foreach(var error in message.ValidationResult.Errors) { switch (error.PropertyName) { case "CompanyName": modelState.AddModelError("Name",error.ErrorMessage); break; case "Interval": modelState.AddModelError("Interval",error.ErrorMessage); break; } } } return viewModel; } public class CompanyAccountRegistrationRequestMessageValidator : AbstractValidator<CompanyAccountRegistrationRequestMessage> { public CompanyAccountRegistrationRequestMessageValidator() { RuleFor(x=>x.CompanyName).NotEmpty().WithMessage("Please specify a Company Name"); RuleFor(x=>x.Interval).ExclusiveBetween(0,10).WithMessage("Interval value must be between 1 and 9"); } } This two validation Rules works perfectly. I want to apply validation to Mobile too, ie: mobile number should be unique. How can I do this? Modification: public class CompanyAccountViewModel { public string Name { get; set; } public float Interval { get; set; } public List<string> Mobile { get; set; } }
Model Binding in List
I have a list inside ViewModel but when I make the Post to the Controller it's not binding it and shows an error on Parameter: null, Value: Null. If you could help me out on this. ViewModel: public class OperaRateImportRuleViewModel { public SelectList ResortsSelectList { get; set; } [Required] [DisplayName("Resorts")] public List<string> ListResort { get; set; } public List<Rules> ExtraRuleList { get; set; } public OperaRateImportRuleViewModel() { ExtraRuleList = new List<Rules>(); ListResort = new List<string>(); } } Controller: public ActionResult EditRules(string id) { OperaRateImportRuleViewModel model = new OperaRateImportRuleViewModel(); var getRulesForResort = service.GetAllOperaRateRules().Where(x => x.ResortCode == id).ToList(); foreach (var item in getRulesForResort) { var ruleModel = new Rules() { Id = item.Id, IsReferenceRule = item.IsReferenceRule, PercentVariation = item.PercentVariation == null ? 0 : Decimal.Round(item.PercentVariation.Value, 2), RateCode = item.RateCode, ResortCode = item.ResortCode, RoomType = item.RoomType, SingleRoomDifference = item.SingleRoomDifference == null ? 0 : Decimal.Round(item.SingleRoomDifference.Value, 2), SupplementValue = item.SupplementValue == null ? 0 : Decimal.Round(item.SupplementValue.Value, 2) }; model.ExtraRuleList.Add(ruleModel); } return View(model); } [HttpPost] public ActionResult EditRules(OperaRateImportRuleViewModel model) { foreach (var item in model.ExtraRuleList) { var rule = service.GetAllOperaRateRules().Where(x => x.Id == item.Id).FirstOrDefault(); rule.RateCode = item.RateCode; rule.ResortCode = item.ResortCode; rule.RoomType = item.RoomType; rule.PercentVariation = item.PercentVariation; rule.SupplementValue = item.SupplementValue; rule.SingleRoomDifference = item.SingleRoomDifference; rule.IsReferenceRule = item.IsReferenceRule; service.Edit(rule); } return RedirectToAction("ManageRules"); } And finally my View: for (int i = 0; i < Model.ExtraRuleList.Count; i++) { #Html.HiddenFor(x => Model.ExtraRuleList[i].Id) <div class="row"> <div class="col-md-2"> <div class="form-group"> #Html.TextBoxFor(x => x.ExtraRuleList[i].ResortCode, new { #class = "form-control" }) </div> </div> <div class="col-md-2"> <div class="form-group"> #Html.TextBoxFor(x => x.ExtraRuleList[i].ResortCode, new { #class = "form-control" }) </div> </div> <div class="col-md-2"> <div class="form-group"> #Html.TextBoxFor(x => x.ExtraRuleList[i].RoomType, new { #class = "form-control" }) </div> </div> <div class="col-md-1"> <div class="form-group"> #Html.TextBoxFor(x => x.ExtraRuleList[i].PercentVariation, new { #class = "form-control textBoxSize" }) </div> </div> <div class="col-md-1"> <div class="form-group"> #Html.TextBoxFor(x => x.ExtraRuleList[i].SupplementValue, new { #class = "form-control textBoxSize" }) </div> </div> <div class="col-md-1"> <div class="form-group"> #Html.TextBoxFor(x => x.ExtraRuleList[i].SingleRoomDifference, new { #class = "form-control textBoxSize" }) </div> </div> <div class="col-md-1"> <div class="form-group"> #Html.LabelFor(m => m.ExtraRuleList[i].IsReferenceRule, new { #class = "checkbox-label" }) #Html.CheckBoxFor(x => x.ExtraRuleList[i].IsReferenceRule) </div> </div> <div class="col-xs-2"> <div class="form-group"> <span id="deleteSeason" title="Delete" onclick="$(this).closest('.row').remove().trigger(review());" class="glyphicon glyphicon-remove text-danger row-action"></span><span> </span> </div> </div> </div> } <input type="submit" value="Edit" class="btn btn-primary" /> Back Error: Error when Binding Much appreciated! Thanks :) EDIT ViewModel Rules: public class Rules { public int Id { get; set; } [DisplayName("Rate Code")] public string RateCode { get; set; } [DisplayName("Resort Code")] public string ResortCode { get; set; } [DisplayName("Room Type")] public string RoomType { get; set; } [DisplayName("Percent Variation")] public decimal? PercentVariation { get; set; } [DisplayName("Supplement Value")] public decimal? SupplementValue { get; set; } [DisplayName("Single Room Difference")] public decimal? SingleRoomDifference { get; set; } [DisplayName("")] public bool IsReferenceRule { get; set; } public string HotelString { get; set; } }
Your error is thrown because your IsReferenceRule property is decorated with [DisplayName("")]. You need to either delete it, or give it a value, for example [DisplayName("Is Reference Rule ")] public bool IsReferenceRule { get; set; } but in any case, you should be using the DisplayAttribute, not the DisplayNameAttribute [Display(Name = "Is Reference Rule ")] Specifically, the error occurs when the public override IEnumerable<ModelValidationResult> Validate(object container) method of DataAnnotationsModelValidator is called. The offending line in the source code is context.DisplayName = Metadata.GetDisplayName(); which returns null because of the missing value in the attribute.
Model' conflicts with the declaration Model on Grid.MVC (ASP.NET)
I have a form and using Grid.MVC to display in same page. When I try run my program, it show error : 'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage.Model'.. Here the sample of my code This is my model public class Course { [DisplayName("Customer Name")] public string customer { get; set; } [DisplayName("Contact")] public string contact { get; set; } [UIHint("DropDownList")] [Required(ErrorMessage = "Please select the package")] public int CoursePackageID { get; set; } [Required] public int CustomerID { get; set; } [Required(ErrorMessage = "The date is required")] [DisplayName("Date Of Register")] public DateTime dtRegister { get; set; } [DisplayName("Payment")] public string payment { get; set; } public List<CourseObject> lCourse { get; set; } public class CourseObject { public int courseId { get; set; } [DisplayName("Package")] public string package { get; set; } [DisplayName("Date Of Register")] public DateTime date_register { get; set; } [DisplayName("Payment")] public string payment { get; set; } } } And this is my CSHTML (Razor) #model BangiProject.Models.Course #using GridMvc.Html #{ ViewBag.Title = "Register"; } <h2> Register</h2> #using (Html.BeginForm()) { #Html.ValidationSummary(true) <fieldset> <legend>Course</legend> <div class="control-label"> #Html.LabelFor(model => model.customer) </div> <div class="form-control-static"> #Html.DisplayFor(model => model.customer) </div> <div class="control-label"> #Html.LabelFor(model => model.contact) </div> <div class="form-control-static"> #Html.DisplayFor(model => model.contact) </div> <div class="editor-label"> Category : </div> <div class="editor-field"> #Html.DropDownListFor(Model => Model.CoursePackageID, new SelectList(ViewBag.CoursePackage as System.Collections.IEnumerable, "id", "course_name", new { #style = "drop-down" }), "-Choose Package-", new { id = "cat" }) </div> <div class="editor-label"> #Html.LabelFor(model => model.dtRegister) </div> <div class="editor-field"> #Html.EditorFor(model => model.dtRegister) #Html.ValidationMessageFor(model => model.dtRegister) </div> <div class="editor-label"> #Html.LabelFor(model => model.payment) </div> <div class="editor-field"> #Html.EditorFor(model => model.payment) #Html.ValidationMessageFor(model => model.payment) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div class="row"> #Html.Grid(Model.lCourse).Columns(columns => { columns.Add(c => c.courseId).Titled("ID") .Sanitized(false) .Encoded(false) .RenderValueAs(o => Html.ActionLink("Edit", "Edit", "Merchant", new { id = o.courseId }, null).ToHtmlString()); columns.Add(c => c.package).Titled("Package").Filterable(true); columns.Add(c => c.date_register).Titled("Date Of Register").Filterable(true); }).WithPaging(25).Sortable(true) </div> <div> #Html.ActionLink("Back to List", "Index") </div> #section Scripts { #Scripts.Render("~/bundles/jqueryval") } The error show on this line #Html.Grid(Model.lCourse).Columns Please advice...
Usually this means that you're using the reserved "Model" keyword erroneously somewhere. In your case: #Html.DropDownListFor(Model => Model.CoursePackageID... Change this to: #Html.DropDownListFor(model => model.CoursePackageID...
Try changing the line in question as below(lowercase 'm')... #Html.Grid(model.lCourse).Columns
Cant seem the get my dropdown menu to work, spent hours looking through this and a tutorial, but I cant seem to get it right
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??
NullReferenceException ASP.NET MVC 5
I have a web application with this controller: public class ServiceRequestController : Controller { [Authorize(Roles = "Customer")] public ActionResult Create() { return View(); } [Authorize(Roles = "Customer")] public ActionResult CreateNewUserAccount() { return View(); } [Authorize(Roles = "Customer")] [HttpPost] public ActionResult CreateNewUserAccount(ServiceRequest serviceRequest) { if (ModelState.IsValid) { serviceRequest.Log.Id = User.Identity.GetUserId().ToString(); serviceRequest.Log.DateTimeLogged = System.DateTime.Now; serviceRequest.LogID = db.Logs.Max(item => item.LogID); serviceRequest.EstimatedResolveDate serviceRequest.CalculateEstimatedResolveDate(); db.ServiceRequests.Add(serviceRequest); db.SaveChanges(); return RedirectToAction("AllServiceRequests", "Log"); } return View(serviceRequest); } The serviceRequest.Log.Id = User.Identity.GetUserId().ToString(); (And any preceding line if this is commented out) throws a null reference exception. I presume the serviceRequest is somehow null? The ActionLink which requests the CreateNewUserAccount() page is: #Html.ActionLink("New User Account", "CreateNewUserAccount", "ServiceRequest") I'm not sure how to resolve this exception? The model is: public partial class ServiceRequest { public int ServiceRequestID { get; set; } public Nullable<int> LogID { get; set; } public string RequestType { get; set; } [DisplayName("Additional Information")] [Required] [StringLength(200)] public string AdditionalInformation { get; set; } public DateTime EstimatedResolveDate { get; set; } [Required] [DisplayName("Delivery Date")] public DateTime DeliveryDate { get; set; } public virtual Log Log { get; set; } public DateTime CalculateEstimatedResolveDate() { return System.DateTime.Now.AddDays(3); } } View code: #model OfficiumWebApp.Models.ServiceRequest #{ ViewBag.Title = "New User Account"; } #using(Html.BeginForm("CreateNewUserAccount", "ServiceRequest", FormMethod.Post)) { #Html.AntiForgeryToken() <div class="form-horizontal"> #Html.ValidationSummary(true) <div class="form-group"> #Html.LabelFor(model => model.RequestType, new { #class = "control-label col-md-2" }) <div class="col-md-3"> <div class="editor-field"> #Html.TextBoxFor(model => model.RequestType, new { #Value = ViewBag.Title, #readonly = "readonly" }) #Html.ValidationMessageFor(model => model.RequestType) </div> </div> </div> <div class="form-group"> #Html.Label("Name of Account Holder", new { #class = "control-label col-md-2" }) <div class="col-md-3"> <div class="editor-field"> #Html.TextBox("AccountName") #Html.ValidationMessageFor(model => model.RequestType) </div> </div> </div> <div class="form-group"> #Html.Label("Department", new { #class = "control-label col-md-2" }) <div class="col-md-3"> <div class="editor-field"> #Html.TextBox("Department") #Html.ValidationMessageFor(model => model.RequestType) </div> </div> </div> <div class="form-group"> #Html.Label("Location", new { #class = "control-label col-md-2" }) <div class="col-md-3"> <div class="editor-field"> #Html.TextBox("Location", null, new { id = "Location" })) #Html.ValidationMessageFor(model => model.RequestType) </div> </div> </div> <div class="form-group"> #Html.LabelFor(model => model.AdditionalInformation, new { #class = "control-label col-md-2" }) <div class="tags"> <div class="col-md-10"> #Html.TextAreaFor(model => model.AdditionalInformation) #Html.ValidationMessageFor(model => model.AdditionalInformation) </div> </div> </div> <div class="form-group"> #Html.LabelFor(model => model.DeliveryDate, new { #id = "VisitDateLabel", #class = "control-label col-md-2" }) <div class="col-md-3"> <div class="editor-field"> #Html.JQueryUI().DatepickerFor(model => model.DeliveryDate).Inline(false) #Html.ValidationMessageFor(model => model.DeliveryDate) </div> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button> </div> </div> </div> }
You need to return the view i.e. [Authorize(Roles = "Customer")] public ActionResult CreateNewUserAccount() { var model = new ServiceRequest(); model.Log = new Log(); return View(model); } In your view you need to add a model reference too at the top i.e. #model ServiceRequest You could also initialise the Log object in your model as follows: public class ServiceRequest { public ServiceRequest() { Log = new Log(); } .... } An action link will not post your model back, you need to include it within a form and include all the model values that you want to be updated on the client i.e. #using (Html.BeginForm("CreateNewUserAccount", "ServiceRequest", FormMethod.Post)){ #Html.EditorFor(m => m.AdditionalInformation) ... <input type="submit" value="submit" /> Update Taken from the below comments, this was resolved by creating a new log on post i.e. var log = new Log { Id = User.Identity.GetUserId().ToString(), DateTimeLogged = System.DateTime.Now, LogID = db.Logs.Max(item => item.LogID) }; serviceRequest.Log = log;