Adding a image to database in ASP.NET MVC 5 - c#

I'm trying to add an image to a database table using ASP.NET MVC with Entity Framework.
I've made a migration of existing ASP.NET MVC table named 'AspNetUsers' and added some new columns in it.
One of the columns is ProfilePicture, and it is byte[] type.
When I'm trying to register new user I'm expecting that user provide it's profile picture among other data.
Here is ApplicationUser class with newly added properties:
public class ApplicationUsers : IdentityUser
{
public string Name { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string DateOfBirth { get; set; }
public byte[] ProfilePicture { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUsers> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
To get the image into table I'm using class wrapper named ExtendedIdentityModels. This class inherits from RegisterViewModel class and it has only one property UserProfilePicture, type of HttpPostedFileBase, for getting the image from user's page.
public class ExtendedIdentityModels : RegisterViewModel
{
public HttpPostedFileBase UserProfilePicture { get; set; }
}
I've changed Register method in the controller to add this new properties to database:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(ExtendedIdentityModels model)
{
if (ModelState.IsValid)
{
if (model.UserProfilePicture != null)
{
if (model.UserProfilePicture.ContentLength > (4 * 1024 * 1024))
{
ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
return View();
}
if (!(model.UserProfilePicture.ContentType == "image/jpeg" || model.UserProfilePicture.ContentType == "image/gif"))
{
ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
}
}
byte[] data = new byte[model.UserProfilePicture.ContentLength];
model.UserProfilePicture.InputStream.Read(data, 0, model.UserProfilePicture.ContentLength);
var user = new ApplicationUsers() { UserName = model.Email, Email = model.Email, Name = model.Name, LastName = model.LastName, City = model.City, DateOfBirth = model.DateOfBirth.ToString(), ProfilePicture = data };
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);
}
// If we got this far, something failed, redisplay form
return View(model);
}
For interacting with user I use following View, on the bottom of this code is a part for adding ProfilePicture.
#model StudentBookApp.Models.ExtendedIdentityModels
#{
ViewBag.Title = "Register";
}
#*<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>*#
<link href="~/Content/datepicker.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap-datepicker.js"></script>
<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.Name, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Name, 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.City, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.City, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.DateOfBirth, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.DateOfBirth, new { #class = "datepicker 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">
#Html.LabelFor(m => m.ProfilePicture, new { #class = "col-md-2 control-label"})
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserProfilePicture, new {type = "file"})
#Html.ValidationMessage("CustomMessage")
</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>
}
<script type="text/javascript">
$(function () {
$('.datepicker').datepicker();
})
</script>
Almost everything goes well, but for model.UserProfilePicture I get null value. For some reason it doesn't get pass from View. What I'm doing wrong? I've been stuck for hours trying to find possible mistake, but no success. This kind of 'mechanism' for inserting image into table use to work well in MVC 4... Does someone sees what I'm missing and what's wrong in this kind of approach?

Nothing to do with MVC or c#, it's HTML ;) /edit Would also like to thank you for all the detail in the question since it was very thorough.
Your form needs enctype="multipart/form-data"
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form", enctype="multipart/form-data" }))

public ActionResult AddImage(Brand model,HttpPostedFileBase image1)
{
var db = new H_Cloths_SaloonEntities();
if (image1!=null)
{
model.Brandimage = new byte[image1.ContentLength];
image1.InputStream.Read(model.Brandimage,0,image1.ContentLength);
}
db.Brands.Add(model);
db.SaveChanges();
ViewBag.Path = "image uploaded Successfully...!";
return View(model);
}

Related

How do you see if the application works when using App_Data SQL Server Database?

Is there someone, who can help me, my registration page and login does not seem to authenticate well. My question how do i see if using App_Data on your Project writes this to the database? Must i also needs to reference as well on my Web.Config, the connection string? I havent done this before some useful examples could easily help me, i can work around it and understand it better.
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser() { UserName = model.UserName };
user.Email = model.Email;
user.ConfirmedEmail = false;
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage(
new System.Net.Mail.MailAddress("ggcobani#gmail.com", "Web Registration"),// This does not send any notification and need some help here, checked under spam nothing to see.
new System.Net.Mail.MailAddress(user.Email));
m.Subject = "Email confirmation";
m.Body = string.Format("Dear {0}<BR/>Thank you for your registration, please click on the below link to complete your registration: {1}", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.Email }, Request.Url.Scheme));
m.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.mydomain.com");
smtp.Credentials = new System.Net.NetworkCredential("ggcobani#gmail.com", "password");
smtp.EnableSsl = true;
smtp.Send(m);
return RedirectToAction("Confirm", "Account", new { Email = user.Email });
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
// View
#model ContentManagementSystem.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.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.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">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-info" value="Register" />
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

Invalid username or password eroor page

I'm setting up a Car Sales project and I want an error page whenever I enter wrong username or password.
I have tried with the [HandleError] attribute, now I'm trying with Membership.ValidateUser. I'm a bit confused about which one I should use all I know is HandlerError attribute is for specific errors.
[HttpPost]
public ActionResult Login(User user)
{
using (CarsDBEntities db = new CarsDBEntities())
{
var usr = db.Users.Single(u => u.Email == user.Email && u.Password == user.Password);
if (usr != null)
{
Session["UserId"] = usr.UserId.ToString();
Session["Email"] = usr.Email.ToString();
Session["FirstName"] = usr.FirstName.ToString();
Session["LastName"] = usr.LastName.ToString();
return RedirectToAction("LoggedIn");
}
if (!Membership.ValidateUser(usr.Email, usr.Password))
{
ModelState.AddModelError(string.Empty, "The user name or password is incorrect");
return View(user);
}
return View();
}
}
This is my view
#model Car_Sales.Models.User
#{
ViewBag.Title = "Login";
}
<h2>Login</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</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">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Login" class="btn btn-default" />
</div>
</div>
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
I expected it to show an error which tells the user that he/she entered incorrect credentials.
Why don't you just redirect to a new View or Action or Controller?
Example:
if (!Membership.ValidateUser(usr.Email, usr.Password))
{
return RedirectToAction("Error","SomeAction")
}

Using AspNetUsers.Id in a form

What I'm wanting is for a person to register (using existing register page) then get directed to a form where their AspNetUsers.Id = UserId (on my CreateProfile page). CreateProfile is the page you are directed to when you have successfully registered. As you can see in the image in the address bar you can see the user id but it won't appear in the input box.
AccountController
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);
// Registered user is given the applicant role by default
UserManager.AddToRole(user.Id, "Applicant");
// 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");
ViewBag.UserId = user.Id;
//return RedirectToAction("Index", "Home");
return RedirectToAction("CreateProfile", new { controller = "Admin", UserId = user.Id });
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
CreateProfile View
#model NAA.Data.Profile
#{
ViewBag.Title = "CreateProfile";
}
<h2>Create Profile</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Profile</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ApplicantName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ApplicantName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ApplicantName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ApplicantAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ApplicantAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ApplicantAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", 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.UserId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserId, new { htmlAttributes = new { #class = "form-control", } })
#Html.ValidationMessageFor(model => model.UserId, "", 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", "GetProfile", new { controller = "Profile", action = "GetProfile" })
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Image of CreateProfile
Controller Action
you have two main problems:
In Register action you pass userId value using ViewBag and later use RedirectToAction. You cannot use ViewBag for this scenario, because value will loss. Check here
You don't assign UserId value on input box [CreateProfile view].
To solve it:
Capture UserId value in CreateProfile Get Action and later assign in ViewBag to pass value to View. Two forms:
a. Use MVC bind, set a variable:
// Get: Admin/CreateProfile
public ActionResult CreateProfile(string UserId) // <== here
{
ViewBag.UserId = UserId;
return View();
}
b. Use request object to get value.
// Get: Admin/CreateProfile
public ActionResult CreateProfile()
{
ViewBag.UserId = Request.Params["UserId"]; // <== here
return View();
}
Optional: you could save UserId value using Session Object in Register Action. Maybe I would like this because avoid before code. Check here.
Finally assign UserId value on input box in CreateProfile view using #Value:
new { htmlAttributes = new { #class = "form-control", #Value=
ViewBag.UserId }
I.E:
<div class="form-group">
#Html.LabelFor(model => model.UserId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserId, new { htmlAttributes = new { #class = "form-control", #Value= ViewBag.UserId } })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>

Returning Linq value in controller and passing it to View

Having a problem returning and passing the desired values to the View. I run the LINQ query in LINQPad4 and it returns the correct results. I feel I'm missing something simple here. I've using this post HERE as a reference
Im getting the
CS1061: 'IEnumerable' does not contain a definition for 'FirstName' and no extension method 'FirstName' accepting a first argument of type 'IEnumerable' could be found (are you missing a using directive or an assembly reference?)ERROR.
\
When I run and step through the code i dont see any values and the message I'm given is
Message = "Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context."
UPDATE
Changing the View from #model IEnumerable<Login.Models.EditProfile> to #model Login.Models.EditProfile Helped with the CS1061 Error I was having and as for the LINQ query not working please look at the accepted answer below by Titian.
Any help would be greatly appreciated.
Let me know If there is more information I can provide.
/ Controller /
public ActionResult Edit(int? id)
{
using (TDBEntities db1 = new TDBEntities())
{
var user = (from a in db1.ExternalUsers
join b in db1.ExternalUserEmails on a.ExternalUserID equals b.ExternalUserID
join c in db1.ExternalUserPhones on a.ExternalUserID equals c.ExternalUserID
where a.ExternalUserID.Equals(id)
select new EditProfile {ExternalUserID = a.ExternalUserID, FirstName = a.FirstName, LastName = a.LastName, EmailAddress = b.EmailAddress, PhoneNumber = c.PhoneNumber });
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
}
/Model/
public partial class EditProfile
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string PhoneNumber { get; set; }
public int ExternalUserID { get; set; }
}
/View/
#model IEnumerable<Login.Models.EditProfile>
#using Login.Helpers
#{
ViewBag.Title = "Update Employee";
}
<h2></h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Update Employee</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.FirstName, "First Name:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, "Last Name:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailAddress, "Email Address:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PhoneNumber, "Phone Number:", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PhoneNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="resetPw control-label col-md-2 ">Reset Password</label>
<div> #Html.CheckBox("ResetPassword", false, new { #style = "margin: 10px 15px 0;" }) <i>(check to reset)</i></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>
}
<div>
#Html.ActionLink("Back to List", "Index")
You want to add a FirstOrDefault to your query. Select will return a value (of type IQueryable<User>) even if there are no values (an empty result). You actually want the first value in that result or null if there are no matching results:
var user = (from a in db1.ExternalUsers
join b in db1.ExternalUserEmails on a.ExternalUserID equals b.ExternalUserID
join c in db1.ExternalUserPhones on a.ExternalUserID equals c.ExternalUserID
where a.ExternalUserID == id
select new EditProfile {ExternalUserID = a.ExternalUserID, FirstName = a.FirstName, LastName = a.LastName, EmailAddress = b.EmailAddress, PhoneNumber = c.PhoneNumber })
.FirstOrDefault();

url in resetpassword email not returning view

im reseting my password in mvc using email,the code looks fine i can send token to email.but when i click on link in email it doesn,t redirect me to the reset password page
here is my code in emailreset action
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
//SendSmsBusiness objap = new SendSmsBusiness();
RegisterBusiness reg = new RegisterBusiness();
if (ModelState.IsValid)
{
ApplicationUser user = new ApplicationUser();
user = reg.UserManager.FindByEmail(model.Email);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
if (user != null)
{
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol:Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
{
ModelState.AddModelError("", "The user does not exist");
return View();
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
i don,t know if my request.url.scheme is null because i do have a resetpassword page. here is its view.
#model Template.Model.ResetPasswordViewModel
#{
ViewBag.Title = "Reset password";
}
<h2>#ViewBag.Title.</h2>
#using (Html.BeginForm("ResetPassword", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="panel panel-default">
<div class="panel-heading " style="background-color: green;"></div>
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(m => m.Code, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Code, 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.TextBoxFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
</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>
}
#section Scripts {
#System.Web.Optimization.Scripts.Render("~/bundles/jqueryval")
}
any help appreciated.
the resetpassword controller
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
RegisterBusiness reg = new RegisterBusiness();
if (ModelState.IsValid)
{
ApplicationUser user = new ApplicationUser();
user = reg.UserManager.FindByEmail(model.Email);
if (user == null)
{
ModelState.AddModelError("", "No user found.");
return View();
}
IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
else
{
AddErrors(result);
return View();
}
}
// If we got this far, something failed, redisplay form
return View(model);
}

Categories