how to add phone number field in registeration page of mvc application - asp.net-mvc

i want to add phone number field on default registration page of MVC5 Web Application.
and when a user register with given info the user data store in default database of AspNetUsers table in PhoneNumber column.
here is my code for register View.
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Number, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Number, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
and here is code for register view model.
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
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; }
[Required(ErrorMessage = "Your must provide a PhoneNumber")]
[Phone]
[Display(Name = "Phone Number")]
public string Number { get; set; }
}
String number is also used in Manage.so i use the same name.but when a user register its phone number is not showing on database table.

All you need to do is include the phone number in the ApplicationUser like this:
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, PhoneNumber = model.Phone };
You can find that object in the
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, PhoneNumber = model.Phone };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
return View(model);
}
function in the AccountController.cs in a fresh MVC5 project. You can check the AspNetUsers table to see where it went.
It is probably wiser to not store your user data in that table, but create a seperate table for things like phone numbers, etc. That way you can keep your AccountController uncluttered and lean.
For the record, I just did a 'Create new project > MVC' in my VS2012. Nothing was changed from the default settings the new project came with except adding the Phone property to the model and an input field to the view, just like you did.

Related

MVC Admin reset of User Password

After a lot of messing around, and with some excellent help from ADyson, I got this working.
On my system, when an admin user logs in, a link appears for them to go into the user management system. This provides a list of users, the ability to create another user, delete them, or change their details.
Also, when ANY user logs in they are able to change their own password. However, if a user forgets their password, the admin user must reset the password. I'm not emailing them a link or anything fancy. In the "List Users" bit in the admin screen, there is an Actions column that contains links to edit, delete, show details, and reset password.
I have an ApplicationUsersController that contains the functions to edit, delete, etc. I have a series of ApplicationUsers views called Create, Edit, Delete, Details, Edit, Index. Most of this code was generated when I created an ApplicationUsersController and chose to create the views. There is also a ResetUserPasswordsViewModel as well. Here is the ResetPassword view:
#model ICWeb.Models.ResetUserPasswordViewModel
#{
ViewBag.Title = "Reset User Password";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.Title</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "Please fix the errors displayed", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.NewPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NewPassword, new { htmlAttributes = new { #class = "form-control", #autofocus = "autofocus" } })
#Html.ValidationMessageFor(model => model.NewPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Reset Password" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
In the controller I have:
// GET: /ApplicationUsers/ResetPassword
public ActionResult ResetPassword(string id)
{
return View(new ResetUserPasswordViewModel() { Id = id });
}
//POST: /ApplicationUsers/ResetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetUserPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
ApplicationDbContext context = new ApplicationDbContext();
UserStore<ApplicationUser> store = new UserStore<ApplicationUser>(context);
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(store);
string userId = model.Id;
string newPassword = model.NewPassword;
string hashedNewPassword = UserManager.PasswordHasher.HashPassword(newPassword);
ApplicationUser cUser = await store.FindByIdAsync(userId);
await store.SetPasswordHashAsync(cUser, hashedNewPassword);
await store.UpdateAsync(cUser);
return RedirectToAction("Index");
}
After a lot of messing around, I re-did this function. The view loads now and I can type in 2 new passwords. When I submit, the ResetPassword function runs. I can see when I step through the code it has the passwords I typed, and by editing the GET function to populate the model with the Id, I now get the Id of the user. The whole controller access is limited to users with admin permissions, so unless you're an admin you can't do anything here.
In my ResetUserPasswordModel I have:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace ICWeb.Models
{
public class ResetUserPasswordViewModel
{
public string Id { 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; }
}
}
All sorted, and the help was, and is, very much appreciated.
In the system I'm developing (but not yet completed or tested) I've got this written. It works so should be a good starting point. Note that the view model takes care of mis-match passwords so that is covered for you already.
I use Direct Injection for the User Manager - just replace my _userManager with your own instance, however you create it.
#model Models.ResetPasswordViewModel
#{
ViewBag.Title = "Reset password";
}
<div class="container">
#if (ViewBag.Error != null)
{
<div class="alert-danger mb-2">Error(s) occured : #ViewBag.Error</div>
#Html.ActionLink("Back to List", "AllUsers", null, new { #class = "btn btn-outline-primary" })
}
else
{
using (Html.BeginForm("ResetPassword", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary("", new { #class = "text-danger" })
#Html.HiddenFor(x => x.Id)
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control", #readonly = "" } })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "control-label" })
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "control-label" })
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
<div class="form-group d-flex">
#Html.ActionLink("Back to User Edit", "EditUser", "Account", new { userId = Model.Id }, new { #class = "btn btn-outline-primary" })
<input type="submit" value="Reset Password" class="btn btn-primary ml-auto" />
</div>
}
}
</div>
public class ResetPasswordViewModel
{
[Display(Name = "User Id")]
public string Id { get; set; }
[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; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = _userManager.FindById(model.Id);
IdentityResult result = null;
if (user != null)
{
string code = await _userManager.GeneratePasswordResetTokenAsync(user.Id);
result = await _userManager.ResetPasswordAsync(user.Id, code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account", model);
}
}
// return errors
var s = new System.Text.StringBuilder();
//
foreach (var e in result.Errors)
{
if (s.Length > 0)
{
s.Append(", ");
}
s.Append(e);
}
ViewBag.Error = s.ToString();
return View();
}

Update password for user account in mvc 5

I'm currently working on user account and so far i've managed to work upon register and login panel with email confirmation process. Here i'm stuck in forget password option. I'm using ado.net entity framework. All i have to do is to change password for the registered email. This is what i've done so far.
Note: getting the error in controller action method
the entity type is not part of the model for the current context
Edit
I have a table named registration attached to the DBContext class. And i'm trying to update the records (particularly the password field) for the forger password option. I made the property class UpdateAcccount.cs with validation as attached below. In order to update the password, I retrieved the row matching with email id. And then transferring the updated password in the database.
This time i'm getting the error of "password does not match" although there's no field of confirm password in the database(registration table) + i even tried to use bind(exclude) attribute for confirm password but that didn't work either.
Controller class
[HttpPost]
public ActionResult UpdateAccount(UpdateAccount account)
{
string message = "";
bool status = false;
if (ModelState.IsValid)
{
account.Password = Crypto.Hash(account.Password);
account.ConfirmPassword = Crypto.Hash(account.ConfirmPassword);
using (TravelGuide1Entities entity = new TravelGuide1Entities())
{
try
{
var v = entity.Registrations.Where(a => a.Email == account.Email).FirstOrDefault();
if (v != null)
{
v.Password = account.Password;
entity.Entry(v).State = System.Data.Entity.EntityState.Modified;
entity.SaveChanges();
return RedirectToAction("Login");
}
}
catch(Exception e)
{
}
}
}
return View();
}
UpdateAccount.cs
public class UpdateAccount
{
[Display(Name = "Email")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Email id required")]
public string Email { get; set; }
[Display(Name = "New Password")]
[Required(AllowEmptyStrings = false, ErrorMessage = "Password required")]
[DataType(DataType.Password)]
[MinLength(6, ErrorMessage = "Minimum 6 character required")]
public string Password { get; set; }
[Display(Name = "Confirm Password")]
[DataType(DataType.Password)]
[Compare("Password", ErrorMessage = "Password do not match")]
public string ConfirmPassword { get; set; }
}
UpdateAccount.cshtml
#model Travel.Models.UpdateAccount
#{
ViewBag.Title = "UpdateAccount";
}
<h2>UpdateAccount</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>UpdateAccount</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

Why is my form validation not firing?

I am building a Form in my view based on a View Model. the View model has [Required] on every field and Validation rules, but when checking the Model.IsValid it keeps coming back true even when all of the form fields are blank or null. Here is the View:
#model CommunityWildlifeHabitat.ViewModel.CreateAdminViewModel
#{
ViewBag.Title = "CreateAdmin";
}
<h2>Create Admin</h2>
#using (Html.BeginForm("CreateAdmin", "Admin", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-6 control-label" })
<div class="col-md-6">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.FirstName, new { #class = "col-md-6 control-label" })
<div class="col-md-6">
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.LastName, new { #class = "col-md-6 control-label" })
<div class="col-md-6">
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-6 control-label" })
<div class="col-md-6">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-6 control-label" })
<div class="col-md-6">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-5 col-md-6">
<input type="submit" class="btn btn-habitat" value="Create Admin" />
</div>
</div>
}
Here is my ViewModel
public class CreateAdminViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email")]
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; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
Here is the Controller get and post
[Authorize]
public ActionResult CreateAdmin(int? id)
{
var model = new CreateAdminViewModel();
if (id == null) { return RedirectToAction("Index", "Communities"); }
if (User.Identity.IsAuthenticated)
{
var userId = User.Identity.GetUserId();
var superUser = db.CommunityTeams.Where(x => x.UserId == userId && x.RoleId == 4).Any();
// If User is not a SuperUser (Administrator)
if (superUser == false)
return RedirectToAction("Index", "Communities");
}
return View(model);
}
[Authorize]
[HttpPost]
public ActionResult CreateAdmin(FormCollection fc)
{
var model = new CreateAdminViewModel();
model.Email = fc["Email"];
model.FirstName = fc["FirstName"];
model.LastName = fc["LastName"];
model.Password = fc["Password"];
model.ConfirmPassword = fc["ConfirmPassword"];
if (ModelState.IsValid)
{ }
return RedirectToAction("index", "Admin");
}
On your HttpPost you have a model type of FormCollection
public ActionResult CreateAdmin(FormCollection fc)
Should it be of your model type? Else always true state?
public ActionResult CreateAdmin(CreateAdminViewModel fc)

asp.net mvc confirm password always fails

I'm using VS2017 Community. Also forgot to mention, This happens in IE11 and not in Chrome.
I generate the default template for an MVC application with Individual user accounts. I hit F5, goto Register, fill in the fields but every time, no matter what, the form does not post and I get the error from the model validations (The password and confirmation password do not match.). As a refresher:
[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; }
I have tried several emails and passwords. I confirmed that I followed the rules in IdentityConfig.cs for the password.
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
I'm following a Pluralsight course and they do exactly what I'm doing without errors, except he seems to be using an older version of Visual Studio.
I've searched for this problem six ways to sunday and everything that comes refers to older implementations of MVC where the Compare attribute wasnt fully implemented yet or was implemented differently.
Can anyone else confirm/deny this works out of the box for them?
And heres the post action, again all default, all template code.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
Just for grins, heres the default view it generates.
#model PSMVCAuth.Models.RegisterViewModel
#{
ViewBag.Title = "Register";
}
<h2>#ViewBag.Title.</h2>
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class
= "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label"
})
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-
label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-
control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

What could be causing for ASP.NET MVC form to not properly submit/deserialize?

This looks like it should be working, yet the form submits with model not properly deserialized. Using latest ASP.NET MVC from nuget. .NET 4.5
A very standard user-registration View/Controller.
View:
#model Alertera.Portal.Web.Models.RegisterViewModel
#{
ViewBag.Title = "Register";
}
<h2>#ViewBag.Title.</h2>
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#*#Html.ValidationSummary()*#
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.FirstName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.LastName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
Controller:
// POST: /Account/Register
[AcceptVerbs(HttpVerbs.Post)]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new User
{
UserName = model.UserName,
FirstName = model.FirstName,
LastName = model.LastName
};
user.SetEmail(model.Email);
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
_bus.Publish(new UserCreated(user));
await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
All of the posts are coming in with model being empty or forgery token not present (depends if I enable or disable verficiation). I'm simply stumped and don't know where to look.
** EDIT **
If I disable antiforgery, ModelState is invalid, all of the fields in the model are empty and error messages state that fields are required.
I'm using Autofac with MVC extensions and Model binder is registered like so:
builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
builder.RegisterModelBinderProvider();
Autofac is working in general, as controller is instantiated properly and is injected with propery dependencies.
Edit 2:
Created a custom binder by inheriting from the DefaultModelBinder, per suggestion, so that I could see the transformation. It looks like the bindingContenxt's model is null
The view model itself is here:
public class RegisterViewModel
{
[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]
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string FirstName { get; set; }
}
After a full day of trubleshooting, updating all of the nuget packages, making sure that web.config's are all tight and contain proper assembly redirects, routes are neat, and even repair of .NET framework and other time consuming and irrelevant activities, I've finally figured this out:
A few weeks prior, we've introduced an Autofac binding that would capture serialized HttpContext along with other relevant data for when the logging framework would need it. (Imagine being able to log request information alongside a full exception stack inside a business object without polluting business logic with session/logging data.)
Unfortunately, as a part of the binding creation, the HttpContext was being serialized by Json.net and not at the time of the logging of the event, but at the time of the binding.
Apparently, when Json.net seralizes HttpContext, it actually reads the streams inside it for the first time, causing the submitted form data to be read, so that when Controller is instantiated and data for it is posted, the streams have already been read and Request.Form colection is empty.
Simple fix to only create a delegate to serialize HttpContext appears to have fixed the issue

Resources