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")
}
Related
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();
}
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)
I'm new to MVC 5 and my problem is that every time I tried entering the same password in the Confirm Password field, it always fires the validation message [Compare]. Is this a common problem ?
Here's my code in Model:
[Required]
[StringLength(MaxUserNameLength)]
[Display(Name = "Username")]
public virtual string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(MaxPasswordLength)]
public virtual string Password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "Doesn't Match")]
public string ConfirmPassword { get; set; }
and here is my code in the View
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserName, "", 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.PasswordFor(m => m.Password, new { #class = "form-control required" })
#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.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control required" })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", new { #class = "text-danger" })
</div>
</div>
#model FailTracker.Models.LoginUser //your model
#{
ViewBag.Title = "Test";
}
#using (Html.BeginForm())
{
// your view code goes here
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
}
This is working fine. I didnt see any problem with the code.
Hey guys i am coding in MVC 5 code first now i have this table below when i want to edit a Cell number or an email and my changes are saved on the database my Picture got deleted i do not know why because i did not change it. every time i Edit other information the Picture got delete when i save my changes
[Key]
public int Member_Id { get; set; }
[Required]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Please enter minimum of 3 characters")]
[RegularExpression(#"^[a-zA-Z\s?]+$", ErrorMessage = "Pease enter valid name!")]
[Display(Name = "First Name")]
public string Name { get; set; }
[Required]
[RegularExpression(#"^[a-zA-Z\s?]+$", ErrorMessage = "Pease enter valid Surname!")]
[StringLength(20, MinimumLength = 3, ErrorMessage = "Please enter minimum of 3 characters")]
[Display(Name = "Surname")]
public string Surname { get; set; }
[Required]
[RegularExpression(#"^(\d{10})$", ErrorMessage = "Cellphone number must be 10 digits!")]
[Display(Name = "Cell Number")]
public string Cell_Number { get; set; }
[Required]
[RegularExpression(#"^(\d{13})$", ErrorMessage = "id must be 13 digits!")]
[Display(Name = "ID Number")]
public string ID_Number { get; set; }
[Required]
[RegularExpression(".+\\#.+\\..+", ErrorMessage = "Please enter a valid email address")]
[Display(Name = "Email Address")]
public string Email { get; set; }
[Required]
[Display(Name = "Physical Address")]
public string Address { get; set; }
[Display(Name = "Owner")]
public bool Owner { get; set; }
[Display(Name = "Driver")]
public bool Driver { get; set; }
[Display(Name = "Rank Manager")]
public bool Rank_Manager { get; set; }
[Display(Name = "Profile Picture")]
public byte[] Picture { get; set; }
public string alter_Text { get; set; }
public string ImageMimeType { get; set; }
public virtual ICollection<Taxi> Taxi { get; set; }
and this is my controller
public ActionResult EditPick(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Member member = db.Member.Find(id);
if (member == null)
{
return HttpNotFound();
}
return View(member);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPick(/*[Bind(Include = "Member_Id,Name,Surname,Cell_Number,ID_Number,Email,Address,Owner,Driver,Rank_Manager,Picture,alter_Text,ImageMimeType")]*/ Member member,HttpPostedFileBase image)
{
try
{
var picturee = new Member();
if (image != null)
{
if (image.ContentLength > 2 * 1024 * 1024)
{
ModelState.AddModelError("CustomError", "The File size be not more than 2 MB");
return View();
}
if (!(image.ContentType == "image/jpeg" || image.ContentType == "image/gif"))
{
ModelState.AddModelError("CustomError", "The File Allowed : jpeg and gif");
return View();
}
if (image != null)
{
member.ImageMimeType = image.ContentType;
member.Picture = new byte[image.ContentLength];
image.InputStream.Read(member.Picture, 0, image.ContentLength);
}
}
picturee.Member_Id = member.Member_Id;
picturee.Name = member.Name;
picturee.Surname = member.Surname;
picturee.Cell_Number = member.Cell_Number;
picturee.ID_Number = member.ID_Number;
picturee.Email = member.Email;
picturee.Address = member.Address;
picturee.Owner = member.Owner;
picturee.Driver = member.Driver;
picturee.Rank_Manager = member.Rank_Manager;
picturee.Picture = member.Picture;
picturee.ImageMimeType = member.ImageMimeType;
picturee.alter_Text = member.alter_Text;
db.Entry(picturee).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DataException)
{
ModelState.AddModelError("", "Sorry can not update contact Administrator");
}
return View(member);
}
This is my View when posting
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Member</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Member_Id)
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Cell_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Cell_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Cell_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ID_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ID_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ID_Number, "", new { #class = "text-danger" })
</div>
</div>
<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.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Owner, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Owner)
#Html.ValidationMessageFor(model => model.Owner, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Driver, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Driver)
#Html.ValidationMessageFor(model => model.Driver, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Rank_Manager, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Rank_Manager)
#Html.ValidationMessageFor(model => model.Rank_Manager, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Picture, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#{
if (Model.Picture != null)
{
string imageBase64 = Convert.ToBase64String(Model.Picture);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="#imageSrc" width="100" height="100" />
}
}
#Html.ValidationMessageFor(model => model.Picture, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.alter_Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.alter_Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.alter_Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageMimeType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImageMimeType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImageMimeType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
As said in comments, you need to add a Input=File Name=Image in your view to post back the file with the changes to your profile picture, but the most important thing to do, is to read back the member info from you database and not build a new one instance of a member.
Actually your new member has no info on the previous image if the view don't post back a file and when you save you loose the image bytes.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPick(Member member,HttpPostedFileBase image)
{
try
{
var picturee = new context.Member.Find(member.Member_Id);
if(picturee != null)
{
.....
}
// Now you can start updating the other fields and then save.
// This is not needed -> picturee.Member_Id = member.Member_Id;
picturee.Name = member.Name;
picturee.Surname = member.Surname;
....
In this way you reload the image bytes in case the View don't post back a file to read
In the view you need to add the appriate code to post back the profile image if the user want it updated.
<div class="form-group">
#Html.LabelFor(model => model.Picture, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input name="Image" type="file" />
</div>
#{
if (Model.Picture != null)
{
string imageBase64 = Convert.ToBase64String(Model.Picture);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="#imageSrc" width="100" height="100" />
}
}
#Html.ValidationMessageFor(model => model.Picture, "", new { #class = "text-danger" })
</div>
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.