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.
Related
I am working with MVC3.
I have a dropdown that I need to set the default value from the database.
When I select a value in the dropdownlist I get a postback and the value I selected is selected even after the postback. How do I get the default value, <--Select Project--> as selected value again after the postback?
Models
namespace BugTracker.Models
{
public class BugModel
{
public List<BugModel> InsertBug {get; set;}
public List<BugModel> Bugs { get; set; }
public Int16 BugID { get; set; }
[Required(ErrorMessage = "Title is required")]
public string Title { get; set; }
[Required(ErrorMessage = "Description is required")]
public string Description {get; set;}
[Required(ErrorMessage = "Version is required")]
public string Version { get; set; }
[Required(ErrorMessage = "BuildNumber is required")]
public string BuildNumber { get; set; }
[Required(ErrorMessage = "CreatedDate is required")]
public string CreatedDate { get; set; }
[Required(ErrorMessage = "GetDate is required")]
public string GetDate { get; set; }
public List<BugModel> GetProjects { get; set; }
public int ProjectID { get; set; }
[Required(ErrorMessage = "ProjectName is required")]
public string ProjectName { get; set; }
public List<BugModel> GetEmployee {get; set;}
public int EmployeeID { get; set; }
public int CreatedByID { get; set; }
[Required(ErrorMessage = "EmployeeName is required")]
public string EmployeeName {get;set;}
[Required(ErrorMessage = "CreatedBy is required")]
public string CreatedBy { get; set; }
public List<BugModel> GetCategory { get; set;}
public int CategoryID { get; set; }
[Required(ErrorMessage = "Category is required")]
public string Category { get; set;}
public List<BugModel> GetSeverity { get; set;}
public int SeverityID { get; set; }
[Required(ErrorMessage = "Severity is required")]
public string Severity { get; set; }
public List<BugModel> GetPriority { get; set; }
public int PriorityID { get; set; }
[Required(ErrorMessage = "Prirority is required")]
public string Prirority { get; set;}
public List<BugModel> GetReleasePhase { get; set;}
public int ReleasePhaseID { get; set; }
[Required(ErrorMessage = "ReleasePhase is required")]
public string ReleasePhase { get; set;}
public List<BugModel> GetTypes { get; set; }
public int TypeID { get; set; }
[Required(ErrorMessage = "Type is required")]
public string Type { get; set; }
public List<BugModel> GetBugHistory { get; set; }
[Required(ErrorMessage = "AssignTo is required")]
public string AssignTo { get; set; }
}
}
Controllers
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BugDetails(FormCollection form,string Projects,string Prirority,string CreatedBy,BugModel model)
{
var modelList = new List();
ViewBag.Projects = new SelectList(GetProjects(), "ProjectId", "ProjectName");
ViewBag.Prirority = new SelectList(GetPriority(), "PriorityID", "Prirority");
ViewBag.CreatedBy = new SelectList(GetEmployee(), "EmployeeID", "EmployeeName");
using (SqlConnection conn = new SqlConnection(#"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=BugtrackerNew;Data Source=SSDEV5-HP\SQLEXPRESS"))
{
SqlCommand dCmd = new SqlCommand("Filter", conn);
dCmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dCmd.Parameters.Add(new SqlParameter("#ProjectID", Projects));
dCmd.Parameters.Add(new SqlParameter("#PriorityID",Prirority));
dCmd.Parameters.Add(new SqlParameter("#CreatedByID",CreatedBy));
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
model.BugID = Convert.ToInt16(ds.Tables[0].Rows[i]["BugID"]);
model.Title = ds.Tables[0].Rows[i]["Title"].ToString();
model.Description = ds.Tables[0].Rows[i]["Description"].ToString();
conn.Close();
return View(modelList);
}
}
View
using (Html.BeginForm())
{ %>
<%: Html.DropDownList("Projects", (SelectList)ViewBag.Projects)%>
<%: Html.DropDownList("Prirority", (SelectList)ViewBag.Prirority, "Select Project")%>
<%: Html.DropDownList("CreatedBy", (SelectList)ViewBag.CreatedBy, "--Select Project--")%>
Now I want to get default value when the page is posted back. But in MVC we have no page load method, so how do I do this?
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.
I am having trouble with Model.IsValid on a property that's not required.
Here's the code.
BeginForm in the Edit.cshtml file
#using (Html.BeginForm("Edit", "Member", FormMethod.Post, new { enctype = "multipart/formdata" }))
{
#Html.Partial("_MemberForm", Model.Member)
}
MemberEditViewModel: (used for the Edit.cshtml file)
public class MemberEditViewModel
{
public MemberFormModel Member { get; set; }
}
MemberFormModel:
public class MemberFormModel : ICreateMemberCommand, IValidatableObject
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string SocialSecurityNumber { get; set; }
[Required]
public int PinCode { get; set; }
[Required]
public char Gender { get; set; }
public string Email { get; set; }
[Required]
public string Address { get; set; }
[Required]
public string ZipCode { get; set; }
[Required]
public string ZipAddress { get; set; }
public string Phone { get; set; }
public string Phone2 { get; set; }
[Required]
public string City { get; set; }
[Required]
public int CountryId { get; set; }
//not required (but still displaying error it's required)
public Membership Membership { get; set; }
// not required (displaying error it's required)
public PunchCard PunchCard { get; set; }
public bool IsActive { get; set; }
block of _MemberForm.cshtml (partial)
<fieldset>
<dl>
<dt>#Html.LabelFor(m => m.Id)</dt>
<dd>#Html.TextBoxFor(m => m.Id, new { disabled = "disabled", #readonly = "readonly" })</dd>
<dt>#Html.LabelFor(m => m.PinCode)</dt>
<dd>#Html.EditorFor(m => m.PinCode)</dd>
<!-- problem with membership, maybe with the .FromData/ToDate ? -->
<dt>#Html.LabelFor(m => m.Membership)</dt>
<dd>#Html.EditorFor(m => m.Membership.FromDate, new { #name = "Membership" }) -
#Html.EditorFor(m => m.Membership.ToDate, new { #name="Membership"})</dd>
<!-- problem with punch card, maybe with the .Times ? -->
<dt>#Html.LabelFor(m => m.PunchCard)</dt>
<dd>#Html.EditorFor(m => m.PunchCard.Times, new { #name = "PunchCard" })</dd>
</dl>
</fieldset>
The MemberController Edit Action
// POST: /Members/10002/Edit
[HttpPost]
public ActionResult Edit(FormCollection formValues, MemberFormModel memberForm)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if(IsSaveOperation(formValues)){
if(TryUpdateMember(memberForm)){
return RedirectToAction("Details", "Member", new {id = memberForm.Id});
}
}
var mm = new MemberEditViewModel{ Member = memberForm };
return View(mm);
}
Membership.cs
public class Membership
{
public Membership(){ /* empty constructor */}
public Membership(int id, int memberId, DateTime fromDate, DateTime toDate)
{
Id = id;
MemberId = memberId;
FromDate = fromDate;
ToDate = toDate;
}
public int Id { get; set; }
public int MemberId { get; set; }
[DataType(DataType.Date)]
public DateTime FromDate { get; set; }
[DataType(DataType.Date)]
public DateTime ToDate { get; set; }
}
PunchCard.cs
public class PunchCard
{
public PunchCard() { /* empty constructor */ }
public PunchCard(int memberId, int times, DateTime createdDate, DateTime modifiedDate)
{
this.MemberId = memberId;
this.Times = times;
this.CreatedDate = createdDate;
this.ModifiedDate = modifiedDate;
}
public int Id { get; set; }
public int MemberId { get; set; }
public int Times { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime ModifiedDate { get; set; }
}
You see I dont have any [Required] attribute, neither in the MemberFormModel. So how come those two are Required ? Its a mystery.
You should not be using both the disabled and readonly attribute on your textbox:
#Html.TextBoxFor(m => m.Id, new { disabled = "disabled", #readonly = "readonly" })
I guess the disabled attribute takes precedence and the value of the Id is never sent to the server when you submit the form. That's why you get a modelstate error. Because your id property is required. Now you will be probably tell me that it is not decorated with the [Required] attribute but this doesn't matter. Since you have declared it as a non-nullable integer it is implicitly required and the framework automatically makes it required. If you don't want this to happen you should declare it as a nullable integer.
So back to your view, if you want to only display id, without allowing the user to modify it, use readonly:
#Html.TextBoxFor(m => m.Id, new { #readonly = "readonly" })
Obviously don't think that if you made a textbox readonly, the user cannot modify it. The normal user will not. But a hacker could always put whatever value he wants in this textbox and forge a request. So absolutely do not rely on this as some sort of security or something.
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")
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>