Should I validation in WEB.UI Models folder? - asp.net-mvc-3

I have done custommembership as this link:
http://www.brianlegg.com/post/2011/05/09/Implementing-your-own-RoleProvider-and-MembershipProvider-in-MVC-3.aspx
My soulution have two project : CameraStore.Domain and CameraStore.WebUI. In CameraStore.Domain porject, i have an entity named User like this:
public int UserID { get; set; }
[Required]
[Display(Name = "User name")]
public string Username { 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; }
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[Display(Name = "City")]
public string City { get; set; }
[Required]
[Display(Name = "Ward")]
public string Ward { get; set; }
[Required]
[Display(Name = "User name")]
public string Address { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone")]
public string Phone { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
public int RoleID { get; set; }
public virtual Role Role { get; set; }
public virtual ICollection<Order> Order { get; set; }
In my Register Controller method i want to insert user into my database. But i have the field ConfirmPassword, how can i valid it if this property never has in User Entity class. I have used a class named AccountUserModels to return 2 List for 2 dropdownlist in my view, can i add the property ConfirmPassword to this class. I dont want to valid by javascript for ConfirmPassword filed in my view.

Hi if i not wrong you want to compare password right?
try this
[Required(ErrorMessage = "New password is required.")]
[DataType(DataType.Password)]
[StringLength(20, MinimumLength = 5)]
[Display(Name = "New password:")]
public string NewPassword { get; set; }
[Required(ErrorMessage = "Confirm password is required.")]
[DataType(DataType.Password)]
[StringLength(20, MinimumLength = 5)]
[Compare("NewPassword")]
[Display(Name = "Confirm password:")]
public string RePassword { get; set; }
Controller
[HttpPost]
public ActionResult Register(RegisterViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
return RedirectToAction("Success");
}

Related

Need to know how to pass a model for paypal transaction

I have a simple order form that I created in mvc and when they hit the submit button, I have the user redirected to paypal for payment and then they get redirected back to the original page. I'm trying to find out how to either pass the model information or save it somehow because after payment is complete, my program sends them an email with a copy of their receipt and successful purchase. How do I go about doing this? Please let me know if there is anything else you need to see. I'm still brand new to MVC and I'm trying to figure this all out.
Model
public class WritingAppModel
{
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
[EmailAddress(ErrorMessage = "A Valid Email Address is Required.")]
[Required(ErrorMessage = "Email Address is Required.")]
public string Email { get; set; }
[Phone(ErrorMessage = "A Valid Phone Number is Required.")]
[Required(ErrorMessage = "Phone Number is Required.")]
public string PhoneNumber { get; set; }
[Required(ErrorMessage = "Subject is Required.")]
public string Subject { get; set; }
[Required(ErrorMessage = "Topic is Required.")]
public string Topic { get; set; }
[Required(ErrorMessage = "Document Type is Required.")]
public string DocumentType { get; set; }
[Required(ErrorMessage = "Urgency is Required.")]
public string Urgency { get; set; }
[Required(ErrorMessage = "Number of Pages is Required.")]
public Int16 NumberOfPages { get; set; }
[Required(ErrorMessage = "Requirements are Required.")]
[DataType(DataType.MultilineText)]
[StringLength(200)]
public string Requirements { get; set; }
[Required(ErrorMessage = "Writing Style is Required.")]
public string Style { get; set; }
[Required(ErrorMessage = "Spacing is Required.")]
public string Spacing { get; set; }
[Required(ErrorMessage = "Academic Level is Required.")]
public string AcademicLevel { get; set; }
[Required(ErrorMessage = "Number of Sources is Required.")]
public Int16 NumberOfSources { get; set; }
[Required(ErrorMessage = "Price is Required.")]
[Range(0.01, 10000.00, ErrorMessage = "Your quote is not complete because you haven't completed all of the steps.")]
[DataType(DataType.Currency)]
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Price { get; set; }
public string UnFormattedPrice
{
get
{
return this.Price.ToString();
}
}
[Required(ErrorMessage = "Currency is Required.")]
public string Currency { get; set; }
}

Multiple relationships to UserId in one table

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

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.

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")

ASP.NET MVC3 Eager Client-Validation, FluentHTML and Nested ViewModels

I'm using FluentHTML (from MvcContrib) to layout my HTML mark-up. I want to use eager unobtrusive client-validation provided by jquery.validate library. I got everything working correctly except for properties of nested ViewModels. Example:
public class RegisterPageViewModel
{
[Required(ErrorMessage = "First Name cannot be empty.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name cannot be empty.")]
public string LastName { get; set; }
[Required(ErrorMessage = "Email cannot be empty.")]
[RegularExpression(#"^\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Invalid Email Format.")]
public string Email { get; set; }
[Required(ErrorMessage = "Password field cannot be empty.")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Required(ErrorMessage = "You have to confirm your password.")]
[Compare("Password", ErrorMessage = "Passwords must match.")]
[DataType(DataType.Password)]
public string PasswordConfirm { get; set; }
[Required]
public AddressDto Address { get; set; }
public bool TermsOfUse { get; set; }
[Required(ErrorMessage = "Nickname is required")]
public string Nickname { get; set; }
public string MiddleName { get; set; }
[Required(ErrorMessage = "Birthdate is required")]
public string Birthdate { get; set; }
public string Phone { get; set; }
[Required(ErrorMessage = "Mobile number is required")]
public string Mobile { get; set; }
public string RakimMelieh { get; set; }
public string ReferralNickname { get; set; }
}
It works perfectly for ALL of the properties except for those inside the Address property, although I decorated the properties of the AddressDto with validation attributes as well:
public class AddressDto
{
public int Id { get; set; }
[Required(ErrorMessage = "Address Name is required.")]
public string Name { get; set; }
public string Country { get; set; }
public string District { get; set; }
public string City { get; set; }
public string Area { get; set; }
[Required(ErrorMessage = "Address Details are required.")]
public string Details { get; set; }
public bool IsDefault { get; set; }
}
The same thing happens for other view models as well where there are nested view models inside them. One thing I noticed when inspecting the input fields FireBug is that they always have the valid class on them, even when they're not really valid (according to the annotations decorating their properties).
Any thoughts how I can solve this problem?

Resources