been making a database to store users details when they register and have a login/logout page. All was going dandy until when the database updates in the 'UserController' and I get this error:
> 'Mvcflight.RegistrationEntities' does not contain a definition for
> 'User' and no extension method 'User' accepting a first argument of
> type 'Mvcflight.RegistrationEntities' could be found (are you missing
> a using directive or an assembly reference?)
Of course nothing happens on the actual website and nothing saves to the database.
public ActionResult Register(User U)
{
using (RegistrationEntities dc = new RegistrationEntities())
if (ModelState.IsValid)
{
//you should check duplicate registration here
dc.User.Add(U);
dc.SaveChanges();
ModelState.Clear();
U = null;
ViewBag.Message = "Successfully Registration Done";
}
return View(U);
}
The database can't update I don't know why, any ideas?
Here's my class:
public class User
{
public int Id { get; set; }
[Required(ErrorMessage = "Please provide username", AllowEmptyStrings = false)]
public string userName { get; set; }
[Required(ErrorMessage = "Please provide Password", AllowEmptyStrings = false)]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
[StringLength(50, MinimumLength = 8, ErrorMessage = "Password must be 8 char long.")]
public string userPassword { get; set; }
[Compare("Password", ErrorMessage = "Confirm password dose not match.")]
[DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
public string ConfirmPassword { get; set; }
[Required(ErrorMessage = "Please provide full name", AllowEmptyStrings = false)]
public string fullName { get; set; }
[RegularExpression(#"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+#(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$",
ErrorMessage = "Please provide valid email id")]
public string userEmail { get; set; }
}
And my HTML code:
<h2>Register</h2>
#model Mvcflight.Models.User
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>User</legend>
#Html.AntiForgeryToken()
#if (ViewBag.Message != null)
{
<div style="border:solid 1px green">
#ViewBag.Message
</div>
}
<div class="editor-label">
#Html.LabelFor(model => model.userName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userName)
#Html.ValidationMessageFor(model => model.userName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.userEmail)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userEmail)
#Html.ValidationMessageFor(model => model.userEmail)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.userPassword)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.userPassword)
#Html.ValidationMessageFor(model => model.userPassword)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.fullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.fullName)
#Html.ValidationMessageFor(model => model.fullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Id)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Id)
#Html.ValidationMessageFor(model => model.Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
To note I have another database on the website, both sharing my 'FlightClass'
Thanks for any and all help, let me know if you need more info/code!!
:)
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 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
In my MVC web app I'm attempting to upload a file while submitting a new record to the database but whenever that happens I receive "Object reference not set to an instance on an object" error. Below is my Model:
public class MenteeViewModel
{
public mentee mentee { get; set; }
public guardian guardian { get; set; }
public address address { get; set; }
public email email { get; set; }
public user users { get; set; }
public phnumber phnumber { get; set; }
public econtact econtact { get; set; }
[Display(Name = "School System")]
public int SelectedSSystemId { get; set; }
public IEnumerable<SelectListItem> SSystemItems { get; set; }
[Display(Name = "School")]
public int SelectedSchoolId { get; set; }
public IEnumerable<SelectListItem> SchoolItems { get; set; }
public ssystem ssystems { get; set; }
public school schools{ get; set; }
//This is for UPLOADING image and inserting image information to database
public HttpPostedFileBase File { get; set; }
public image image { get; set; }
}
Below is the section of code from the controller where I actually attempt to upload the file:
[HttpPost]
public ActionResult Create(MenteeViewModel menteeViewModel, HttpPostedFileBase file )
{
if (ModelState.IsValid)
{
var regModel = new RegisterModel();
try
{
DateTime now = DateTime.Now;
menteeViewModel.address.CreatedOn = now;
menteeViewModel.guardian.CreatedOn = now;
menteeViewModel.econtact.CreatedOn = now;
menteeViewModel.email.CreatedOn = now;
menteeViewModel.phnumber.CreatedOn = now;
menteeViewModel.mentee.addresses.Add(menteeViewModel.address);
menteeViewModel.mentee.guardians.Add(menteeViewModel.guardian);
menteeViewModel.mentee.econtacts.Add(menteeViewModel.econtact);
menteeViewModel.mentee.emails.Add(menteeViewModel.email);
menteeViewModel.mentee.phnumbers.Add(menteeViewModel.phnumber);
Regex pattern = new Regex("[-/]");
var strDob = (DateTime) menteeViewModel.mentee.dob;
var newDate = strDob.ToShortDateString();
newDate = pattern.Replace(newDate, "");
regModel.UserName = menteeViewModel.email.email_address;
regModel.Password = newDate;
WebSecurity.CreateUserAndAccount(regModel.UserName, regModel.Password);
Roles.AddUsersToRole(new[] {regModel.UserName}, "User");
menteeViewModel.mentee.active_flag = "N";
menteeViewModel.mentee.flag3 = menteeViewModel.schools.school_id.ToString();
menteeViewModel.mentee.CreatedOn = now;
var vfileName = Guid.NewGuid().ToString() + Path.GetFileName(menteeViewModel.image.image_path);
var path = Path.Combine(Server.MapPath("~/App_Data"), vfileName);
menteeViewModel.File.SaveAs(path);
menteeViewModel.image.image_path = path;
menteeViewModel.mentee.images.Add(menteeViewModel.image);
db.mentees.Add(menteeViewModel.mentee);
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine(" - Property: \"{0}\", Error: \"{1}",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return RedirectToAction("Index");
}
return Create();
}
Below is the View:
BEMentoring.ViewModels.MenteeViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>MenteeViewModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.first_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.first_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.middle_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.middle_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.last_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.last_name)
</div>
<!-- Gender, DOB, Class Grade !-->
<div class="editor-label">
#Html.LabelFor(model => model.mentee.gender)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.gender)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.dob)
</div>
<div class="editor-field">
#Html.JQueryUI().DatepickerFor(model => model.mentee.dob).ChangeYear(new YearDefinition(-20, RelativeTo.SelectedYear), new YearDefinition(2012)).DateFormat("yyyy-mm-dd")
</div>
<div class="editor-label">
#Html.LabelFor(model => model.mentee.class_grade)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.mentee.class_grade)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.address.address1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.address.address1)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.address.city)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.address.city)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.address.state)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.address.state)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ssystems.ssystem_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ssystems.ssystem_id, new SelectList(ViewBag.SSystems as System.Collections.IEnumerable, "ssystem_id","ssystem_name"),
"--Select One--", new {id = "ddlSystem"})
</div>
<div class="editor-label">
#Html.LabelFor(model => model.schools.school_id)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.schools.school_id, new SelectList(ViewBag.Schools as System.Collections.IEnumerable, "school_id","school_name"),
"--Select One--", new {id = "ddlSchool"})
</div>
<div class="editor-label">
#Html.LabelFor(mode => Model.econtact.first_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.econtact.first_name)
</div>
<div class="editor-label">
#Html.LabelFor(mode => Model.econtact.last_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.econtact.last_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.econtact.phone)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.econtact.phone)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.email.email_address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.email.email_address)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.phnumber.area_code)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.phnumber.area_code)
#Html.EditorFor(model => model.phnumber.phone)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.guardian.first_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.guardian.first_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.guardian.middle_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.guardian.middle_name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.guardian.last_name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.guardian.last_name)
</div>
<div>
#Html.LabelFor(model => model.File)
#Html.TextBoxFor(model => model.image.image_path, new {type = "file"})
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
I've searched but haven't been able to find a useful answer to this issue. If there is one that could help me, that I've missed please HELP! Thanks in advance
You are doing this:
<div>
#Html.LabelFor(model => model.File)
#Html.TextBoxFor(model => model.image.image_path, new {type = "file"})
</div>
Chenge it to:
<div>
#Html.LabelFor(model => model.File)
<input name="file" type="file">
</div>
This should map to your viewmodel File property. BTW, the name is not the best... but it should work.
In your controller, you are receiving the posted file as a parameter... not in the model itself... so you need to go get it from that parameter.
Use the HttpPostedFileBase file parameter to work with the file. I see a general lack of boundary checking in the code you posted. Be sure to check for null where objects could be null as in this case.
I have the following view, which fails to validate on Title, and NewsContent. Title validation works but not NewsContent. How can i fix it.
#model Foo.NewsViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm("Create", "News", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
<fieldset>
<legend>Category Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.News.Title)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.News.Title)
#Html.ValidationMessageFor(m => m.News.Title)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.NewsContent)
</div>
<div class="editor-field" id="container">
#Html.TextAreaFor(m => m.News.NewsContent)
#Html.ValidationMessageFor(m => m.News.NewsContent)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.Thumbnail)
</div>
<div class="editor-field">
<input type="file" name="files" id="thumbnail" />
</div>
<div class="editor-label">
#Html.LabelFor(m => m.News.Image)
</div>
<div class="editor-field">
<input type="file" name="files" id="original" />
</div>
<div class="editor-label">
#Html.Label("SelectedCategoryId")
</div>
<div class="editor-field">
#Html.DropDownListFor(m => m.SelectedCategoryId, Model.Categories)
</div>
<div class="editor-label">
Publish
</div>
<div class="editor-field">
#Html.CheckBoxFor(m => m.News.Published, new { #checked = "checked" })
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</div>
}
and here is the model|:
public class News : IStorable
{
[Required]
[Display(Name = "Title")]
public virtual string Title { get; set; }
[Required]
[Display(Name = "Content")]
public virtual string NewsContent { set; get; }
......
Issue: Title validation works but not NewsContent.
Validations is not work, because of using Html.TextAreaFor() helper to render the "NewsContent" property,
Here is the code to make it work:
Change your model as:
Decorate the 'NewsContent' property with [DataType] attribute and set the data type as 'MultilineText'. This will indicates that the editor for this property should be a multi-line text input.
public class News : IStorable
{
[Required]
[Display(Name = "Title")]
public virtual string Title { get; set; }
[Required()]
[Display(Name = "Content")]
[DataType(DataType.MultilineText)]
public virtual string NewsContent { set; get; }
//....
}
In the view use Html.EditorFor() helper instead of Html.TextAreaFor() for the 'News.NewsContent' property.
//....
<div class="editor-label">
#Html.LabelFor(m => m.News.NewsContent)
</div>
<div class="editor-field" id="container">
#*#Html.TextAreaFor(m => m.News.NewsContent)*#
#Html.EditorFor(m => m.News.NewsContent)
#Html.ValidationMessageFor(m => m.News.NewsContent)
</div>
//....