Can somebody please help me?
I want to add more fields to account controller than is provided. I want to see these fields in a table as well. I add fields in a Register class. And I am not sure about ID field I want to use auto increment but do not know how if I do not see a table. In normal database it will do automatically. Thanks.
my
Account model:
public class ChangePasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
public int ID { get; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone")]
public string Phone { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "First line of address")]
public string Address { get; set; }
[DataType(DataType.Date)]
[Display(Name = "DOB => dd/mm/yyyy")]
public DateTime DateOfBirth { get; set; }
[Required]
[PostCode(ErrorMessage= "PostCode is not valid")]
[Display(Name = "Post Code")]
public string PostCode { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { 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; }
}
public class PostCodeAttribute : RegularExpressionAttribute
{
public PostCodeAttribute()
: base(
#"([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-
hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-
Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})")
{
ErrorMessage = "PostCode is invalid";
}
}
Then in AccountController I can create user which has same data fields in a table but Membership do not have this option only
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
You might want to consider SimpleMembership (it's the future) and using your own schema, and then using NuGet to use it with MVC 3.
This is "classic" ASP.NET but should help
http://www.asp.net/web-forms/tutorials/security/membership/storing-additional-user-information-cs
(From here adding more fields to registration form using membership on MySql and MVC 3)
Related
I am working in an ASP MVC project, which uses MvcScaffolding a lot, I have a project and a client model, the thing is that the project has to be relationed with client model in two ways (Billing client and Service Client, and both data are from same client model)
I have no idea how to do this, here are my models
Client Model
public class ClientsX
{
[Key]
public int idcliente { get; set; }
[Required(ErrorMessage = "A Legal ID is required")]
[StringLength(150)]
[Display(Name = "Company Name: ")]
public string CompanyName { get; set; }
[StringLength(150)]
[Display(Name = "Legal ID: ")]
public string LegalID { get; set; }
[Required(ErrorMessage = "A Contact First Name is required")]
[StringLength(150)]
[Display(Name = "First Name: ")]
public string FirstName { get; set; }
[Required(ErrorMessage = "A Contact Last Name is required")]
[StringLength(150)]
[Display(Name = "Last Name: ")]
public string LastName { get; set; }
[Required(ErrorMessage = "A Contact Email Address is required")]
[DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid email address")]
[EmailAddress(ErrorMessage = "Please enter a valid email address")]
[StringLength(150)]
[Display(Name = "Email Address: ")]
public string email { get; set; }
[Required(ErrorMessage = "A Phone Number is required")]
[StringLength(15)]
[Display(Name = "Phone: ")]
public string phone { get; set; }
[Required(ErrorMessage = "An Username is required")]
[MaxLength(50, ErrorMessage = "Your Username cannot exceed 50 characters")]
[RegularExpression(#"^[\S]*$", ErrorMessage = "No White spaces are Accepted")]
[Display(Name = "Username: ")]
public string username { get; set; }
[Required(ErrorMessage = "A Password is required")]
[DataType(DataType.Password)]
[Display(Name = "Password: ")]
public string password { get; set; }
}
Project Model
public class Project
{
[Key]
public int idProject { get; set; }
[Display(Name = "Billing Client")]
[Required(ErrorMessage = "This Field is required")]
public int ClientsXId { get; set; }
[Display(Name = "Client")]
[Required(ErrorMessage = "This Field is required")]
public int ClientsXId { get; set; }
[Display(Name = "Status")]
[Required(ErrorMessage = "This Field is required")]
public int estatusId { get; set; }
}
Yes, I know ClientsXId is repeated, but is on purpose, because I need to have the same data in the project model, but it gives me this error:
Error 5 The type 'SSMS_2._0._1.Models.Project' already contains a definition for 'ClientsXId' D:\PC\Visual Studio 2013\Projects\SSMS-2.0.1\SSMS-2.0.1\Models\ProjectModel.cs 99 20 SSMS_2._0._1
How can I make this work?
I have read lots of other posts/discussions regarding this error and have not found a clear answer.
I have customised ASP.NET Identity to store FirstName and Country as well as username/password/email address, and I'm now having issues actually storing this within the generated tables within my database.
I have already enabled migrations, added a migration and updated the database to reflect the 2 additional fields within my Identity.
Error at IdentityResult result = manager.Create(user, model.Password);
$exception {"The entity type ApplicationUser is not part of the model for the current context."} System.Exception {System.InvalidOperationException}
web.config:
<connectionStrings>
<remove name="DefaultConnection" />
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=WIN8-SUNEETAGU\SQLSERVER;Initial Catalog=UnderConstruction;Integrated Security=True" />
</connectionStrings>
AuthenticationModels.cs
namespace UnderConstruction.Models
{
public class AuthenticationModels
{
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string Country { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<UnderConstruction.Models.AuthenticationModels.ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{}
}
public class RegisterModel
{
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
[Display(Name = "Username")]
public string Username { get; set; }
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
public string ConfirmPassword { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage="Please enter a valid email address.")]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
[Display(Name = "First name")]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Country")]
public string Country { get; set; }
}
}
}
AuthenticationController.cs
public class AuthenticationController : Controller
{
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(AuthenticationModels.RegisterModel model)
{
if (ModelState.IsValid)
{
try
{
var userStore = new UserStore<UnderConstruction.Models.AuthenticationModels.ApplicationUser>();
var manager = new UserManager<UnderConstruction.Models.AuthenticationModels.ApplicationUser>(userStore);
var user = new UnderConstruction.Models.AuthenticationModels.ApplicationUser() { UserName = model.Username, Email = model.Email, FirstName = model.FirstName, Country = model.Country };
IdentityResult result = manager.Create(user, model.Password);
return View("RegisterSuccessful");
}
catch (Exception e)
{
ModelState.AddModelError("", e);
}
}
return View("Register",model);
}
}
I'm thinking it has to do with the nested classes within AuthenticationModels.cs. I'd try moving them outside of the AuthenticationModels class. Example:
namespace UnderConstruction.Models.AuthenticationModels
{
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string Country { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<UnderConstruction.Models.AuthenticationModels.ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{}
}
public class RegisterModel
{
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
[Display(Name = "Username")]
public string Username { get; set; }
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 4)]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
public string ConfirmPassword { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[EmailAddress(ErrorMessage="Please enter a valid email address.")]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)]
[Display(Name = "First name")]
public string FirstName { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Country")]
public string Country { get; set; }
}
}
I just moved everything into the UnderConstruction.Models.AuthenticationModels namespace, instead of having to create an instance of the AuthenticationModels class.
Maybe I've found a solution.
Check the UserManager initialization in Startup.Auth.cs to be like this
UserManagerFactory = () => new UserManager<User>(new UserStore<User>(new MyContext()));
I want to Show particular errors in validation summary and disappear some errors like below:` public class LogOnModel
{
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Username must be entered.")]
[Display(Name = "Kullanıcı Adı")]
public string Username { get; set; }
[Required(ErrorMessage = "Password must be entered.")]
[DataType(DataType.Password)]
[Display(Name = "Parola")]
public string Password { get; set; }
}
How can I filter particular errors in ValidationSummary() ?
Okay so I have a MVC project that auto generates an AccountController AcountModel and the associated views.
I created a database with 3 tables using the model first approach, and generated all the controllers/views for all the CRUD operations.
The database contains a user table with a user id, email and password.
How can I use this user table with the auto generated AccountController for user login and registration?
I will show you registration process only , refering which you can build your login/registration with custom database.
Models:
You will add your custommodel to the AccountModels.cs, So it will have following details:
public class ChangePasswordModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[System.Web.Mvc.Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { 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")]
[System.Web.Mvc.Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class userDetailModel
{
[Key]
public Guid UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string city { get; set; }
public string ConfirmPassword { get; set; }
public string comapny { get; set; }
public int zip { get; set; }
}
Context:
You will add custom context to the Models as below:
public class userDetailsDBContext: DbContext
{
public DbSet<userDetailModel> details { get; set; }
}
Controller:
Now we will modify our AccountController for registration as below:
public class AccountController : Controller
{
private userDetailsDBContext db = new userDetailsDBContext();
// POST: /Account/Register
[HttpPost]
public ActionResult Register(userDetailModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
var newuser = Membership.GetUser(model.UserName);
model.UserId =(Guid)newuser.ProviderUserKey;
db.details.Add(model);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
}
EDIT web.config:
Finally, you will have to add the new context to the connectionstrings as below:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MembershipSample-20121105163515;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MembershipSample-20121105163515.mdf" />
<add name="userDetailsDBContext" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MembershipSample-20121105163515;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-MembershipSample-20121105163515.mdf" />
</connectionStrings>
You can change the database name to whatever you want and put it as your convenience but put the path here correctly.
Hope you have got the idea now...
I think waht you need is to create custom membership provider. This code project article will give you aplace to start.
I have this data model:
public class User
{
public long UserID { get; set; }
[Required(ErrorMessage = "User name is required.")]
[MaxLength(50, ErrorMessage = "User name cannot be longer than 50 characters.")]
public string UserName { get; set; }
[Email]
[Required(ErrorMessage = "Email is required.")]
[MaxLength(100, ErrorMessage = "Email cannot be longer than 100 characters.")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required.")]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
public string Password { get; set; }
[MaxLength(150, ErrorMessage = "Full name cannot be longer than 150 characters.")]
public string FullName { get; set; }
public int UserTypeID { get; set; }
public virtual UserType UserType { get; set; }
public virtual ICollection<Page> Pages { get; set; }
}
and I'm using this model to only edit some fields (password shouldn't be editable):
public class EditUserModel
{
public long UserID { get; set; }
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Email]
[Required(ErrorMessage = "Email is required.")]
[MaxLength(100, ErrorMessage = "Email cannot be longer than 100 characters.")]
public string Email { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Full name")]
[MaxLength(150, ErrorMessage = "Full name cannot be longer than 150 characters.")]
public string FullName { get; set; }
public int UserTypeID { get; set; }
public virtual UserType UserType { get; set; }
}
but I'm confused on how to pass the EditUserModel to my data context to update it. Sorry if seems elementary, but I'm really stumped.
This is the auto-generated edit action that I modified:
[IsAdministrator]
[HttpPost]
public ActionResult Edit(EditUserModel user)
{
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeId", "Name", user.UserTypeID);
return View(user);
}
This is the line I'm having trouble with:
db.Entry(user).State = EntityState.Modified;
The reason I created a custom class was to avoid exposing the password from the view.
This can't work because you're trying to save view model.
You could use AutoMapper to rewrite data from view model to your data model. After that you should be able to save changes.
User userModel = Mapper.Map<EditUserModel, User>(user);
userModel = // todo: get password from database
// todo: attach your model to context and save changes
I'm using Entity Framework Code First and that approach works great.