interact objects in dropdownlist when create in mvc - asp.net-mvc-3

I have 2 classes: User and Role, an user has a role
public class User : IPrincipal
{
public int UserId { get; set; }
[Required]
[Display(Name = "User name")]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Display(Name = "Created date")]
public DateTime CreatedDate { get; set; }
[Required]
[Display(Name = "Password question")]
public string PasswordQuestion { get; set; }
[Required]
[Display(Name = "Password anwser")]
public string PasswordAnswer { get; set; }
[Display(Name = "Active")]
public bool IsApproved { get; set; }
[Display(Name = "Last login date")]
public DateTime LastLoginDate { get; set; }
[Display(Name = "Last password changed date")]
public DateTime LastPasswordChangedDate { get; set; }
[Display(Name = "Last activity date")]
public DateTime LastActivityDate { get; set; }
public virtual Role Role { get; set; }
public virtual IIdentity Identity { get; set; }
public virtual bool IsInRole(string role)
{
if (Role.Name.ToLower() == role.ToLower())
{
return true;
}
return false;
}
}
public class Role
{
public int RoleId { get; set; }
[Required]
[Display(Name = "Role name")]
public string Name { get; set; }
}
I created UserController with read/write entity, in Create method, I created ViewBag.Role contains list of role
public ActionResult Create()
{
ViewBag.Role = new SelectList(db.Roles, "RoleId", "Name");
return View();
}
In create view:
<div class="editor-label">
#Html.LabelFor(model => model.Role)
</div>
<div class="editor-field">
#Html.DropDownList("Role")
#Html.ValidationMessageFor(model => model.Role.RoleId) #* I don't know this is correct? *#
</div>
In create view with HttpPost attribute, when user choose one role, and submit, I can't get a value of role.
Anyone who know the way to add role into user by select dropdownlist? I means, when I drop down list role and select item in there, and submit, I add one user row into table
Thank you

You can expose the RoleId foreign key by adding it as a property of User.
Then your view would look like
<div class="editor-field">
#Html.DropDownListFor(model => model.RoleId, (SelectList)ViewBag.Role)
#Html.ValidationMessageFor(model => model.RoleId)
</div>

Related

MVC drop down list - null error

I have generated Models classes using Entity Framework.
This is what I got:
public partial class Employees
{
public Employees()
{
this.Employees1 = new HashSet<Employees>();
this.Vacations = new HashSet<Vacations>();
}
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Phone { get; set; }
public string JobTitle { get; set; }
public int ManagerID { get; set; }
public string LastUpdatedBy { get; set; }
public Nullable<System.DateTime> LastUpdatedDate { get; set; }
public bool Status { get; set; }
public virtual ICollection<Employees> Employees1 { get; set; }
public virtual Employees Manager { get; set; }
public virtual ICollection<Vacations> Vacations { get; set; }
}
Then I've created View Model for that class:
public class EmployeeViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Phone { get; set; }
public string JobTitle { get; set; }
public int ManagerID { get; set; }
public string ManagerFullName
{
get
{
return FirstName + " " + LastName;
}
}
public bool Status { get; set; }
public virtual ICollection<Employees> Employees1 { get; set; }
public virtual Employees Manager { get; set; }
}
In EmplyeeControler class I have action:
public ActionResult Create()
{
EmployeeViewModel employeeVM = new EmployeeViewModel();
ViewBag.Employees1 = new SelectList(employeeVM.Employees1, "EmployeeID", "ManagerFullName");
return View(employeeVM);
}
And view:
<div class="editor-label">
#Html.LabelFor(model => model.ManagerID, "Manager")
</div>
<div class="editor-field">
#Html.DropDownList("ManagerID", "--- Select Manager ---")
#Html.ValidationMessageFor(model => model.ManagerFullName)
</div>
But I am receiving error on line:
Value cannot be null. Parameter name: items
ViewBag.Employees1 = new SelectList(employeeVM.Employees1, "EmployeeID", "ManagerFullName");
What is wrong in my code?
<div class="editor-label">
#Html.LabelFor(model => model.ManagerID, "Manager")
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ManagerID, (IEnumerable<SelectListItem>)ViewBag.Employees1,"--- Select Manager ---"));
#Html.ValidationMessageFor(model => model.ManagerFullName)
</div>
More Details See this link

validation failing on dropdown MVC

I am using code-first with EF. Validation seems to be failing on a dropdown list with the error System.NullReferenceException: Object reference not set to an instance of an object. This happens when I save a record and I intentionally leave controls empty to test the validation. It happens even if the dropdown list itself has a selection.
here is part of my view:
<div class="editor">
#Html.LabelFor(model => model.EmployeeID)
#Html.DropDownListFor(model => model.EmployeeID, new SelectList(Model.Employees, "Value", "Text"))
#Html.ValidationMessageFor(model => model.EmployeeID)
</div>
If I use a textbox validation works:
<div class="editor">
#Html.LabelFor(model => model.EmployeeID)
#Html.TextBoxFor(model => model.EmployeeID, new { style = "width: 250px;" })
#Html.ValidationMessageFor(model => model.EmployeeID)
</div>
here are my Create controller actions:
public ActionResult Create()
{
var e = iEmployeeRepository.GetAll();
var visitorLogViewModel = new VisitorLogViewModel
{
Employees = e.Select(x => new SelectListItem
{
Value = x.EmployeeID,
Text = x.EmployeeName
})
};
return View(visitorLogViewModel);
}
//
// POST: /VisitorLogs/Create
[HttpPost]
public ActionResult Create(VisitorLog visitorlog)
{
if (ModelState.IsValid) {
iVisitorlogRepository.Add(visitorlog);
iVisitorlogRepository.Save();
return RedirectToAction("Search");
} else {
return View();
}
}
And my viewmodel:
public class VisitorLogViewModel
{
public int Id { get; set; }
[Display(Name = "Visitor Name")]
public string VisitorName { get; set; }
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "Employee ID is required.")]
[Display(Name = "GB Employee")]
public string EmployeeID { get; set; }
[Display(Name = "Visit Reason")]
public string VisitReason { get; set; }
[Display(Name = "Time In")]
public DateTime TimeIn { get; set; }
[Display(Name = "Time Out")]
public DateTime TimeOut { get; set; }
[Display(Name = "GB Employee")]
public string EmployeeName { get; set; }
public IEnumerable Employees { get; set; }
public VisitorLog VisitorLog { get; set; }
}
And my partial model for validation:
[MetadataType(typeof(VisitorLogMetaData))]
public partial class VisitorLog
{
}
public class VisitorLogMetaData
{
[Required(ErrorMessage = "Visitor name is required.")]
[MaxLength(128)]
public string VisitorName { get; set; }
[Required(ErrorMessage = "Company name is required.")]
[MaxLength(128)]
public string CompanyName { get; set; }
[Required(ErrorMessage = "GB Employee is required.")]
[MaxLength(128)]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Visit reason is required.")]
[MaxLength(254)]
public string VisitReason { get; set; }
[Required(ErrorMessage = "Time in is required.")]
public DateTime TimeIn { get; set; }
[Required(ErrorMessage = "Time out reason is required.")]
public DateTime TimeOut { get; set; }
}
And finally my model:
public partial class VisitorLog
{
public int Id { get; set; }
public string VisitorName { get; set; }
public DateTime TimeIn { get; set; }
public DateTime TimeOut { get; set; }
public string CompanyName { get; set; }
public string EmployeeID { get; set; }
public string VisitReason { get; set; }
// Navigation properties
[ForeignKey("EmployeeID")]
public virtual Employee Employee { get; set; }
}
I read there was a bug in MVC razor regarding the DropDownListFor but I don't know if that applies in my situation. I have tried some of the solutions and they didn't work for me. I am using 4.5 framework.
Thanks.
Edit:
One thing I noticed, when I submit the page and the error stops on the dropdown element:
#Html.DropDownListFor(model => model.EmployeeID, new SelectList(Model.Employees, "Value", "Text"))
the Model in Model.Employees is null, like it is loosing its binding when the page is submited.
Ok, I did some fundemental changes to my classes. First, I changed the post method in my controller. Previously I was passing the model to the post, now I am passing the view model and mapping it to the model before saving via my repository:
//
// POST: /VisitorLogs/Create
[HttpPost]
public ActionResult Create(VisitorLogViewModel visitorLogViewModel)
{
var e = iEmployeeRepository.GetAll();
VisitorLog visitorLog = new VisitorLog();
visitorLog.Id = visitorLogViewModel.Id;
visitorLog.VisitorName = visitorLogViewModel.VisitorName;
visitorLog.CompanyName = visitorLogViewModel.CompanyName;
visitorLog.EmployeeID = visitorLogViewModel.EmployeeID;
visitorLog.TimeIn = visitorLogViewModel.TimeIn;
visitorLog.TimeOut = visitorLogViewModel.TimeOut;
visitorLog.VisitReason = visitorLogViewModel.VisitReason;
visitorLogViewModel.Employees = new SelectList(e, "EmployeeID", "EmployeeName");
if (ModelState.IsValid)
{
iVisitorlogRepository.Add(visitorLog);
iVisitorlogRepository.Save();
return RedirectToAction("Search");
} else {
return View(visitorLogViewModel);
}
}
Next, I had to add the "required" attribute (validation) to the viewmodel:
public class VisitorLogViewModel
{
public int Id { get; set; }
[Required(ErrorMessage = "Visitor name is required.")]
[MaxLength(128)]
[Display(Name = "Visitor Name")]
public string VisitorName { get; set; }
[Required(ErrorMessage = "Company name is required.")]
[MaxLength(128)]
[Display(Name = "Company Name")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "GB Employee is required.")]
[MaxLength(16)]
[Display(Name = "GB Employee")]
public string EmployeeID { get; set; }
[Required(ErrorMessage = "Visit Reason is required.")]
[MaxLength(254)]
[Display(Name = "Visit Reason")]
public string VisitReason { get; set; }
[Display(Name = "Time In")]
public DateTime TimeIn { get; set; }
[Display(Name = "Time Out")]
public DateTime TimeOut { get; set; }
[Display(Name = "GB Employee")]
public string EmployeeName { get; set; }
public SelectList Employees { get; set; }
}
Not sure if that is the most effcient method but everything works now. If someone sees something wrong with this method let me know.

EF4 MVC3 model state validation

Using this model:
public class Cases
{
//case data model for call center
//implement lists for all related child tables too
[Key]
public int CasesID { get; set; }
public string CaseNumber { get; set; }
[Required(ErrorMessage = "Customer is Required")]
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
[MaxLength(50)]
public string UserName { get; set; } //get user name from the aspnet membership
[Required(ErrorMessage = "Case Category is Required")]
public int CaseCategoryID { get; set; }
[Required(ErrorMessage = "Technician is Required")]
public int TechnicianID { get; set; }
public virtual Technician Technicians { get; set; }
[Required(ErrorMessage = "Engine Model is Required")]
public int EngineModelID { get; set; }
public virtual EngineModel EngineModel { get; set; }
[MaxLength(50)]
public string BMSWorkorder { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Status is Required")]
public string CaseStatus { get; set; }
[MaxLength(50)]
public string OpenedBy { get; set; }
[Required(ErrorMessage = "Opened Date is Required")]
[DataType(DataType.DateTime)]
public DateTime? OpenedDate { get; set; }
[MaxLength(50)]
public string ClosedBy { get; set; }
[DataType(DataType.DateTime)]
public DateTime? ClosedDate { get; set; }
[MaxLength(50)]
[Required(ErrorMessage="Caller First Name is Required")]
public string CallerFirstName { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Caller Last Name is Required")]
public string CallerLastName { get; set; }
[MaxLength(100)]
public string AdditionalContact { get; set; }
[MaxLength(10)]
[Required(ErrorMessage = "Qualified is Required")]
public string Qualified { get; set; }
public string Description { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "ESN is Required")]
public string ESN { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Mileage is Required")]
public string Mileage { get; set; }
[DataType(DataType.Date)]
public DateTime? DateInService { get; set; }
[MaxLength(50)]
public string ESTR { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "EDS is Required")]
public string EDS { get; set; }
[MaxLength(50)]
public string GensetSerialNumber { get; set; }
[MaxLength(50)]
public string GensetModelNumber { get; set; }
//child Case Notes records
public virtual ICollection<CaseNotes> CaseNotes { get; set; }
//child case attachment records
public virtual ICollection<Attachment> Attachments { get; set; }
//child case complaint records
public virtual ICollection<CaseComplaint> CaseComplaint { get; set; }
//tracking fields
public DateTime? CreatedOn { get; set; }
[MaxLength(50)]
public string CreatedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
[MaxLength(50)]
public string ModifiedBy { get; set; }
}
I am wondering why even though only some of the properties are marked required, the modelstate does not get set valid unless all properties have values when saving.
Am I doing something wrong?
EDIT
Here are my razor elements for the dropdownlist fields in question:
#Html.DropDownList("Qualified", String.Empty)
#Html.ValidationMessageFor(model => model.Qualified)
#Html.DropDownList("EngineModelID", String.Empty)
#Html.ValidationMessageFor(model => model.EngineModelID)
#Html.DropDownList("CaseCategoryID", String.Empty)
#Html.ValidationMessageFor(model => model.CaseCategoryID)
The EngineModelID and CaseCategoryID properties must be nullable integers on your view model if you want to allow empty values. Oooops, you are not using view models.
ASP.NET MVC automatically makes non-nullable types required. You could disable this explicitly in your Application_Start:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
But if you want to do the things properly you should use view models.
The following is absolutely horrible:
#Html.DropDownList("CaseCategoryID", String.Empty)
I guess you have stuffed a SelectList in a ViewBag.CaseCategoryID so the CaseCategoryID does 2 things at the same time: it represents a list and a selected scalar value.
With view models you would use the strongly typed version of those helpers:
#Html.DropDownListFor(x => x.CaseCategoryID, Model.CaseCategories)
where CaseCategories will be an IEnumerable<SelectListItem> property on your view model that the controller would populate.

uploaded image Full Path in MVC3

I am uploading a file in MVC3 my csHtml page is
<div class="editor-label">
#Html.LabelFor(model => model.Resume)
</div>
<div class="editor-field">
<input type="file" name="Resume" id="Resume" />
#* #Html.EditorFor(model => model.ImageData)*#
#Html.ValidationMessageFor(model => model.Resume)
</div>
My Post Method is
[HttpPost]
public ActionResult SignUp(UserView user)
{
try
{
if (ModelState.IsValid)
{
UserManager userManager = new UserManager();
if (!userManager.IsUserLoginIDExist(user.LoginID))
{
// Request.Params["Resume"];
userManager.Add(user,Request.Files["Resume"]);
FormsAuthentication.SetAuthCookie(user.FirstName, false);
return RedirectToAction("Welcome", "Home");
}
}
}
catch
{
return View(user);
}
return View(user);
}
and my Model is
public class UserView
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Contact Number")]
public string ContactNumber { get; set; }
[Required]
[Display(Name = "Login ID")]
public string LoginID { get; set; }
[Required]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[Display(Name = "Resume")]
public string Resume { get; set; }
}
}
I am getting user.Resume's value as full path(C:\test.png) on some machine and on some machine i am getting just name of the file(test.png). Please help me to deal with this miscellaneous issue
You aren't actually saving the file there at the moment. Perhaps you know this and have left the code out for brevity, but ASP.Net's built-in file handling gives you everything you need.
This question gives you all the info you need: File Upload Asp.net Mvc3.0

MVC 3 Dropdowns & Multiple Model ViewModel

I'm pretty new to MVC, but I'm trying to set up a two step user registration system. I have an register model and several other models in a viewmodel called Registration. A user will have a profile based on the register model and then they will select a Producer/Distributor/Restaurant/Importer that they are part of, or create a new one of those. My ViewModel that is returned doesn't validate or pickup the values in my dropdownlists. They populate correctly, but on the post they aren't in the vm. Below is my view/controller/and models. I've been searching the net for 2 days with no luck. Also, if you think my method of registration is wacky, let me know. Thanks!
controller:
public class RegistrationController : Controller
{
private vfContext db = new vfContext();
//
// GET: /Registration/
public ActionResult Register()
{
ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeID", "Name");
ViewBag.ProducerID = new SelectList(db.Producers, "ProducerID", "Name");
ViewBag.PublicationID = new SelectList(db.Publications, "PublicationID", "Name");
ViewBag.ImporterID = new SelectList(db.Importers, "ImporterID", "Name");
ViewBag.DistributorID = new SelectList(db.Distributors, "DistributorID", "Name");
ViewBag.RestaurantID = new SelectList(db.Restaurants, "RestaurantID", "Name");
RegistrationViewModel reg = new RegistrationViewModel();
ViewData.Model = reg;
return View("Registration");
}
[HttpPost]
public ActionResult Register(RegistrationViewModel vm)
{
if (ModelState.IsValid)
{
MembershipCreateStatus createStatus;
//email is userid
Membership.CreateUser(vm.Register.Email, vm.Register.Password, vm.Register.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
Profile current = Profile.GetProfile(vm.Register.Email);
current.FirstName = vm.Register.FirstName;
current.LastName = vm.Register.LastName;
current.Address1 = vm.Register.Address1;
current.Address2 = vm.Register.Address2;
current.City = vm.Register.City;
current.State = vm.Register.State;
current.Postal = vm.Register.Postal;
current.UserTypeID = vm.Register.UserTypeID;
view - i'm having a hard time copying it over, so the issue is with ddls, so here is how I have the user type id one done
#model vf2.Models.RegistrationViewModel
<div class="editor-label">
#Html.LabelFor(model => model.Register.UserTypeID, "User Type")
</div>
<div class="editor-field">
#Html.DropDownList("UserTypeID", String.Empty)
#Html.ValidationMessageFor(m => m.Register.UserTypeID)
</div>
Models:
public class RegistrationViewModel
{
public RegisterModel Register { get; set; }
public Producer Producer { get; set; }
public Distributor Distributor { get; set; }
//public Publication Publication { get; set; }
public Restaurant Restaurant { get; set; }
public Importer Importer { get; set; }
}
Here is my register model.
public class RegisterModel
{
//[Required]
//[Display(Name = "User name")]
//public string UserName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Address")]
public string Address1 { get; set; }
[Display(Name = "Address Cont.")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string Country { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
public int ProducerID { get; set; }
public int DistributorID { get; set; }
public int PublicationID { get; set; }
public int ImporterID { get; set; }
public int RestaurantID { get; set; }
public virtual Producer Producer{ get; set; }
public virtual Distributor Distributor { get; set; }
public virtual Publication Publication { get; set; }
public virtual Importer Importer { get; set; }
public virtual Restaurant Restaurant { get; set; }
[Required]
public int UserTypeID { get; set; }
public virtual UserType UserType { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
producer model:
public class Producer
{
public int ProducerID { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string Country { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public string Website { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public DateTime? UpdatedOn { get; set; }
public Boolean Active { get; set; }
public virtual ICollection<Wine> Wines { get; set; }
}
I think I figured this out by adding a the following to my viewmodel:
public IEnumerable<UserType> UserTypes { get; set; }
public IEnumerable<Producer> Producers { get; set; }
and then this to my view:
#Html.DropDownListFor(m=>m.Register.UserTypeID,new SelectList(Model.UserTypes,"UserTypeID","Name"),"Select account type")

Resources