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?
Related
I have three tables Customer, Loan and LoanHistories. Customer table is related to Loan table in a one-to-many relationship, and the Loan table is related to LoanHistories in one-to-many relationship as well.
The following are the C# classes for these tables:
public class Customer
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Display(Name = "ID NO")]
public int CustomerID { get; set; }
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Phone Number")]
public string PhoneNo { get; set; }
[Display(Name = "Nearest Primary School")]
public string NearestPrimarySchool { get; set; }
[Display(Name = "Photo")]
public string Photo { get; set; }
public ICollection<Loan> loans { get; set; }
// public IEnumerable<LoansHistories> loansHistories { get; set; }
// public ICollection<WorkForLiving> workForLivings { get; set; }
// public ICollection<CustomersCharacterBehavior> customersCharacterBehaviors { get; set; }
}
public class Loan
{
[Key]
public int LoanID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal LoanAmount { get; set; }
[NotMapped]
public decimal TotalRepaidIn { get; set; }
[NotMapped]
public decimal Balance { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Loan Balance")]
private decimal _LoanBalance;
public decimal LoanBalance
{
get { return LoanAmount * interestRate; }
set { _LoanBalance = value; }
}
[Display(Name = "Interest Rate")]
public decimal interestRate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Application Date")]
public DateTime ApplicationDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Disbursement Date")]
public DateTime DisbursmentDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Due Date")]
public DateTime DueDate { get; set; }
[Display(Name = "Defaulted")]
public bool Defaulted { get; set; }
[Display(Name = "Approved")]
public bool Approved { get; set; }
//Navigation property
public int CustomerID { get; set; }
public Customer customer { get; set; }
//public ICollection<LoanComments> loancomments { get; set; }
public ICollection<LoansHistories> loansHistories { get; set; }
}
public class LoansHistories
{
[Key]
public int HistID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
[Display(Name = "Repaid Amount")]
public decimal RePaidIn { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Repayement Date")]
public DateTime RepayementDateDate { get; set; }
[Display(Name = "No of paying interest only")]
public int NoOfPayinyingIntrestOnly { get; set; }
// Navigation properties
public int LoanID { get; set; }
public Loan loan { get; set; }
// Navigation property
// public int CustomerID { get; set; }
// public Customer customer { get; set; }
}
This is the LoansController that loads data from Loans and LoansHistories tables:
[HttpGet]
public async Task<ActionResult<IEnumerable<Loan>>> Getloans()
{
var data = await _context.loans
.Include(lh => lh.loansHistories)
.Select(l => new Loan()
{
TotalRepaidIn = l.loansHistories.Select(lh => lh.RePaidIn).Sum(),
Balance = l.loansHistories.Select(lh => lh.RePaidIn).Sum()-l.LoanAmount,
loansHistories = l.loansHistories,
ApplicationDate = l.ApplicationDate,
Defaulted = l.Defaulted,
DisbursmentDate = l.DisbursmentDate,
DueDate = l.DueDate,
LoanID = l.LoanID,
Approved = l.Approved,
interestRate = l.interestRate,
LoanAmount = l.LoanAmount
}).ToListAsync();
return data;
}
This is the data in JSON format:
[
{
"loanID":1,
"loanAmount":1000.0000,
"totalRepaidIn":202700.0000,
"balance":201700.0000,
"loanBalance":15000.000000,
"interestRate":15.00,
"applicationDate":"2022-03-28T00:00:00",
"disbursmentDate":"2022-03-28T00:00:00",
"dueDate":"2022-04-28T00:00:00",
"defaulted":false,
"approved":true,
"customerID":0,
"customer":null,
"loansHistories":[
{
"histID":1,
"rePaidIn":500.0000,
"repayementDateDate":"2022-03-28T00:00:00",
"noOfPayinyingIntrestOnly":1,
"loanID":1,
"loan":null
}
]
}
]
I want to load data from customer controller but I found entity TotalRepaidIn to be Zero, How can I make it return a value has its returning in loan controller? without having entity totalRepaidIn":0.0
Customer controller:
// GET: api/CustomersApi
[HttpGet]
public async Task<ActionResult<IEnumerable<Customer>>> Getcustomers()
{
return await _context.customers.Include(l=>l.loans).ThenInclude(h=>h.loansHistories).ToListAsync();
}
It returns the following Json data:
[
{
"customerID":30290122,
"firstName":"Isaac",
"lastName":"Kiplagat",
"phoneNo":"0724797768",
"nearestPrimarySchool":"Mokwo",
"photo":"photo",
"loans":[
{
"loanID":1,
"loanAmount":1000.0000,
"totalRepaidIn":0.0,
"balance":0.0,
"loanBalance":15000.000000,
"interestRate":15.00,
"applicationDate":"2022-03-28T00:00:00",
"disbursmentDate":"2022-03-28T00:00:00",
"dueDate":"2022-04-28T00:00:00",
"defaulted":false,
"approved":true,
"customerID":30290122,
"loansHistories":[
{
"histID":1,
"rePaidIn":500.0000,
"repayementDateDate":"2022-03-28T00:00:00",
"noOfPayinyingIntrestOnly":1,
"loanID":1
}
]
}
]
}
]
One way is like the previous did you can select the new Customer instance and set value for it one by one.
Another easier way, you can change your property to below to calculate the RePaidIn:
using System.Linq; //import this namespace...
public class Loan
{
[Key]
public int LoanID { get; set; }
[DataType(DataType.Currency)]
[Column(TypeName = "money")]
public decimal LoanAmount { get; set; }
private decimal _TotalRepaidIn;
[NotMapped]
public decimal TotalRepaidIn
{
get { return loansHistories.Sum(sum => sum.RePaidIn); }
set { _TotalRepaidIn = value; }
}
//other properties
public ICollection<LoansHistories> loansHistories { get; set; } = new List<LoansHistories>();
}
And in your LoansController, you can improve the action to below:
var data = await _context.loans.Include(lh => lh.loansHistories).ToListAsync();
Customer Controller can also get the correct value for TotalRepaidIn.
I have a UserProfile with a UserId. I need to create a relationship to a table Scorecards where there are multiple columns that need to have a relationship with UserId. They are ScorerId, CreatedById, AgentId, ModifiedById, PublishedById ....
I am unsure of how this would be done via code first approach with mvc 4 and entity 5?
Any Help would be appreciated.
public class ScorecardsModel
{
[Key]
public int ScorecardId { get; set; }
[Required]
[Display(Name = "Agent ID")]
public int AgentId { get; set; }
[Required]
[Display(Name = "Agent Name")]
public string AgentName { get; set; }
[Display(Name = "Department")]
public int DepartmentId { get; set; }
[Required]
public DateTime? CreatedOn { get; set; }
[Required]
[Display(Name = "Scorer")]
public int CreatedById { get; set; }
[Required]
[Display(Name = "Call")]
public int CallNum { get; set; }
[Required]
[Display(Name = "Call Date/Time")]
public DateTime? CallDateTime { get; set; }
[Required]
[Display(Name = "Procedural Score")]
[Range(0, 100)]
public int ProceduralScore { get; set; }
[Required]
[Display(Name = "Soft Skills Score")]
[Range(0, 100)]
public int SoftSkillsScore { get; set; }
[Required]
[Display(Name = "Total Score")]
[Range(0, 100)]
public int TotalScore { get; set; }
[Required]
public bool Modified { get; set; }
[Required]
[Display(Name = "Modified By")]
public int ModifiedById { get; set; }
[Required]
[Display(Name = "Modified On")]
public DateTime? ModifiedOn { get; set; }
public bool Completed { get; set; }
[Required]
[Display(Name = "Completed By")]
public int CompletedById { get; set; }
[Required]
[Display(Name = "Completed On")]
public DateTime? CompletedOn { get; set; }
public bool Published { get; set; }
[Required]
[Display(Name = "Published By")]
public int PublishedById { get; set; }
[Required]
[Display(Name = "Published On")]
public DateTime? PublishedOn { get; set; }
[Required]
[Display(Name = "Template")]
public int TemplateId { get; set; }
And UserProfile:
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string DisplayName { get; set; }
Thanks in advance.
Look at the following link Relationships in EF5 - Code First. It might be what you are looking for.
You can also refer to this if you get stuck.
And lastly in this ASP Forum, is some more information
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.
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'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")