Im making a homepage in which i want to have a form that ppl can fill in and then when clicking submit have it sent to a gmail account. I more or less want it to show up as an email without them having to fill in their own email address. I was thinking it would work out fine just sending it from the same email that is receiving it.
Problem is that it wont really get trough.
The procedure is fine since i can see all the information i fill in correctly but it wont send the mail.
This is the controller:
public ActionResult InvitationResponseForm()
{
return View();
}
[HttpPost]
public ViewResult InvitationResponseForm(InvitationResponse model)
{
if (ModelState.IsValid)
{
MailMessage response = new MailMessage();
response.From = new MailAddress("sixtofjun#gmail.com");
response.To.Add("sixtofjun#gmail.com");
response.Subject = model.Name + " " + model.Surname;
string Special = model.SpecialConditions;
string PlusOne = model.PlusOneComment;
bool OneOrTwo = model.PlusOne;
response.Body = model.Name + " " + model.Surname + " " + OneOrTwo + "<br><br>" + Special + "<br>" + PlusOne;
response.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 465);
NetworkCredential basicAuthInfo = new NetworkCredential("sixtofjun#gmail.com", "My password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = basicAuthInfo;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.EnableSsl = true;
return View("InvitationResponseForm", model);
}
else
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
return View();
}
}
And some of the view:
<div class="form-group">
#Html.LabelFor(model => model.PlusOneComment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PlusOneComment)
#Html.ValidationMessageFor(model => model.PlusOneComment)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SpecialConditions, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SpecialConditions)
#Html.ValidationMessageFor(model => model.SpecialConditions)
</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>
Doing this for my pending wedding so really would like some help with it!
Feel free to ask for more info!
Tried alot now but still nothing successful. Can it have something to do with my ssl?
Your gmail smtp port is wrong. You use "smtp.EnableSsl = true;" but still use the 465 port. I use this code and it is sending emails:
var client = new SmtpClient("smtp.gmail.com", 587)
{
Credentials = new NetworkCredential("myusername#gmail.com", "mypwd"),
EnableSsl = true
};
client.Send("myusername#gmail.com", "myusername#gmail.com", "test", "testbody");
Related
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")
}
I want to send an email with a file attachment. when I client send and use the break to check what is the data I am receiving then image file show null in the controller. anyone tells me where is my mistake and what is the problem in my code.so i am sharing controller code ,model and HTML kindly review my code and tell me what is the problem in my code.
Controller
[HttpPost]
public ActionResult Index(EmployeeModel obj)
{
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("abc#hotmail.com", "******");
MailMessage msgobj = new MailMessage();
msgobj.To.Add(obj.ToEmail);
msgobj.From = new MailAddress("abc#hotmail.com");
msgobj.Body = obj.EMailBody;
msgobj.Subject = obj.EmailSubject;
msgobj.CC.Add(obj.EmailCC);
msgobj.Bcc.Add(obj.EmailBCC);
if(obj.imageFile !=null)
{
msgobj.Attachments.Add(new Attachment(obj.imageFile.InputStream.ToString(), obj.imageFile.FileName));
}
client.Send(msgobj);
ViewBag.Success = "Email Send Successfully";
return View();
}
Model:
[DataType(DataType.EmailAddress),Display(Name = "TO")]
[Required]
[Key]
public string ToEmail { get; set; }
[DataType(DataType.MultilineText)]
[Display(Name ="Body")]
[Required]
public string EMailBody { get; set; }
[Display(Name ="Subject")]
[Required]
public string EmailSubject { get; set; }
[Display(Name ="CC")]
[DataType(DataType.EmailAddress)]
public string EmailCC { get; set; }
[Display(Name ="BCC")]
[DataType(DataType.EmailAddress)]
public string EmailBCC { get; set; }
public HttpPostedFileWrapper imageFile { get; set; }
public string imageUrl { get; set; }
HTML
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee Model</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ToEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ToEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ToEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EMailBody, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EMailBody, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EMailBody, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailSubject, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailSubject, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailSubject, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailCC, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailCC, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailCC, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailBCC, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailBCC, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailBCC, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.imageFile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="imageFile" name="imageFile" accept="image/jpeg, image/png" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10 text-success">
#ViewBag.Status
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
First, you should modify this property:
public HttpPostedFileWrapper imageFile { get; set; }
to this one:
public HttpPostedFileBase imageFile { get; set; }
Second, add enctype="multipart/form-data to the BeginForm helper:
#using (Html.BeginForm("Index", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
// form contents
}
Also you're using Gmail SMTP engine but your network credential setting seem to use Hotmail, both of them have different settings. Here are examples of correct settings:
Gmail SMTP
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("xxxxx#gmail.com", "******");
MailMessage msgobj = new MailMessage();
msgobj.To.Add(obj.ToEmail);
msgobj.From = new MailAddress("xxxxx#gmail.com");
msgobj.Body = obj.EMailBody;
msgobj.Subject = obj.EmailSubject;
msgobj.CC.Add(obj.EmailCC);
msgobj.Bcc.Add(obj.EmailBCC);
if (obj.imageFile != null && obj.imageFile.ContentLength > 0)
{
msgobj.Attachments.Add(new Attachment(obj.imageFile.InputStream, obj.imageFile.FileName));
}
client.Send(msgobj);
Hotmail SMTP
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("xxxxx#hotmail.com", "******");
MailMessage msgobj = new MailMessage();
msgobj.To.Add(obj.ToEmail);
msgobj.From = new MailAddress("xxxxx#hotmail.com");
msgobj.Body = obj.EMailBody;
msgobj.Subject = obj.EmailSubject;
msgobj.CC.Add(obj.EmailCC);
msgobj.Bcc.Add(obj.EmailBCC);
if (obj.imageFile != null && obj.imageFile.ContentLength > 0)
{
msgobj.Attachments.Add(new Attachment(obj.imageFile.InputStream, obj.imageFile.FileName));
}
client.Send(msgobj);
you should change
#using (Html.BeginForm())
with
#using (Html.BeginForm("Index", "YourControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
What does enctype='multipart/form-data' mean?
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);
}
We've got a page which currently contains a four or five partial views, but is something that could grow. At the moment, there's two POST actions, for two entirely different database functions.
If we try doing the create function on another, the redirect then results in an "Object reference not set to an instance of an object." error, which is then relating to the other POST partial view.
Is there a way to stop this? Essentially, it seems to me that the post for one partial view is trying to interact with the other. Any ideas?
Thanks
Bulletins Controller for Creating:
[HttpPost]
public ActionResult CreateMain(BulletinsViewModel viewModel)
{
if (ModelState.IsValid)
{
BulletinsContext.tblBulletins.Add(new tblBulletin
{
ID = viewModel.BulletinID,
BulletinDisplayDate = viewModel.BulletinDisplayDate,
BulletinFilename = viewModel.MainBulletinName,
IsSixthForm = viewModel.IsSixthForm
});
//For loop to delete bulletins
//If bulletin folder has more than 10 files in
//Delete the oldest file, itererate till only 10 remain
{
DirectoryInfo dir = new DirectoryInfo(#"D:\Inetpub\WWWroot\intranet\Dashboard\Dashboard\Files\Bulletins");
List<FileInfo> filePaths = dir.GetFiles().OrderByDescending(p => p.CreationTime).ToList();
for (int index = filePaths.Count() - 1; index > 9; index--)
{
var fileNames = filePaths[index].Name;
//Delete from directory
filePaths[index].Delete();
//Remove from collection to restart the loop
filePaths.RemoveAt(index);
}
}
//Save changes to database
BulletinsContext.SaveChanges();
//Return to main bulletins index page
return RedirectToAction("~/Home/Index");
}
return View(viewModel);
}
Bulletins Create View:
#model Dashboard.Viewmodels.BulletinsViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.BulletinDisplayDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BulletinDisplayDate, new { htmlAttributes = new { #class = "form-control", #id = "datepicker-basic", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.BulletinDisplayDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MainBulletinName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="input-group">
#Html.EditorFor(model => model.MainBulletinName, new { htmlAttributes = new { #class = "form-control", #Value = "Select File...", #readonly="readonly" } })
<span class="input-group-addon" href="javascript:;" onclick="moxman.browse({ fields: 'MainBulletinName', extensions: 'pdf', path: 'D:/Inetpub/WWWroot/intranet/Dashboard/Dashboard/Files/Bulletins' });" style="cursor: pointer;"><i class="fa fa-upload"></i></span>
#Html.ValidationMessageFor(model => model.MainBulletinName, "", new { #class = "text-danger" })
</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>
}
<script type="text/javascript" src="~/Scripts/tinymce/plugins/moxiemanager/js/moxman.loader.min.js"></script>
Printer Credits Create Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult PrinterCredits(PrinterCreditsViewModel viewModel)
{
if (ModelState.IsValid)
{
//Send the email if credits are added..
//Create a bunch of variables for the email
//Create the email body etc
var fromAddress = "";
string toName = Request.Form["Username"].ToUpper();
string AmountOfCredits = Request.Form["AmountAdded"];
string Plural = "";
string Title = "";
string AddedByWho = User.Identity.Name.Split('\\')[1];
System.DateTime AddedWhen = DateTime.Now;
if (AmountOfCredits == "1")
{
Plural = " printer credit has ";
Title = "Printer Credit Added!";
}
else
{
Plural = " printer credits have ";
Title = "Printer Credits Added!";
}
var toEmail = toName + "";
var subject = AmountOfCredits + Plural + "been added to your account, " + toName;
string body = "";
//Create an SMTP client for sending an email
var smtp = new SmtpClient
{
Host = "",
Port = 25,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
};
//Populate the SMTP client and encode the body for the HTML
using (var message = new MailMessage(fromAddress, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true,
BodyEncoding = System.Text.Encoding.UTF8
})
//Try to send the email. If sent, insert data.
//Redirect back to original page
//Take current printer credit from and update with fund + cost
try
{
//Link the viewmodel and the database together
PartialViewContext.tblPrinterCredits.Add(new tblPrinterCredit
{
Username = viewModel.Username,
AmountAdded = viewModel.AmountAdded,
AddedBy = AddedByWho,
AddedWhen = viewModel.AddedWhen,
Money = viewModel.AmountAdded * 0.02
});
Nullable<double> cost = viewModel.AmountAdded * 0.02;
//Update the printer credit fund and insert into tblOption
tblOption fund = (
from n in PartialViewContext.tblOptions
where n.ID == 1
select n).First();
fund.PrinterCreditFund = fund.PrinterCreditFund + cost;
PartialViewContext.SaveChanges();
message.CC.Add("");
smtp.Send(message);
Response.Redirect("~/Home/Index");
}
//If it fails, go chicken oriental (only a redirect, will eventually become a crazy message)
catch
{
smtp.Send(message);
Response.Redirect("~/Home/Index");
}
}
return View(viewModel);
Printer Credits View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="panel">
<div class="panel-heading">
<span class="panel-icon">
<i class="fa fa-print"></i>
</span>
Add Printer Credits - #Costings
</div>
<div class="panel-body">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-3">User:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.Username, new { htmlAttributes = new { #class = "form-control", #id = "Username", #name = "Username", #maxlength = "6" } })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Amount:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.AmountAdded, new { htmlAttributes = new { #class = "form-control", #id = "AmountAdded", #onkeyup = "Update()", #Value = 0 } })
#Html.ValidationMessageFor(model => model.AmountAdded, "", new { #class = "text-danger", #type="number" })
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Cost:</label>
<div class="col-xs-8">
#Html.EditorFor(model => model.TotalCost, new { htmlAttributes = new { #class = "form-control", #id = "TotalCost", #readonly = "readonly", #Value = "0" } })
#Html.ValidationMessageFor(model => model.TotalCost, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1 col-md-10">
<input type="submit" value="Add Printer Credits" class="btn btn-primary btn-gradient dark btn-block" />
#Html.EditorFor(model => model.AddedBy, new { htmlAttributes = new { #class = "form-control", #Value = User.Identity.Name.Split('\\')[1], #Style = "display: none;" } })
#Html.ValidationMessageFor(model => model.AddedBy, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
</div>
}
<script type="text/javascript">
$(document).ready(
function () {
Update();
$('#AmountAdded, #TotalCost')
.keyup(function () {
Update();
})
}
);
function Update() {
var cost = 2
var one = $('#AmountAdded'),
two = $('#TotalCost');
two.val(parseInt(one.val()) * cost / 100);
}
</script>
<script type="text/javascript">
document.getElementById('Username').focus()
</script>
Just figured out that I need to tell the form which action and controller to use, despite the fact two different controllers are running the views. But anyway, an example is:
#using (Html.BeginForm("CreateMain", "Bulletins", FormMethod.Post, new { }))
In my application I am trying to get a forgot password to work. I am trying to send an email to the user when he/she inputs his or her user name, sends them and email, they click on that link, and are brought back into the website and changes their password. Only thing is that my linq query is wrong an is not checking to see if the username exists in the database. Is this the right way to go by getting a forget password to work?
Here is my code
Controller
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgetPassword()
{
return View();
}
// Post: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ForgetPassword(ForgetPasswordModel model, string UserName)
{
string emailAddress = (from i in db.UserProfiles
where i.UserName.Equals(model.Username)
select i.Email).Single();
if (!string.IsNullOrEmpty(emailAddress))
{
string confirmationToken =
WebSecurity.GeneratePasswordResetToken(model.Username);
dynamic email = new Email("ChngPasswordEmail");
email.To = emailAddress;
email.UserName = model.Username;
email.ConfirmationToken = confirmationToken;
email.Send();
return RedirectToAction("ResetPwStepTwo");
}
return RedirectToAction("InvalidUserName");
}
Model
public class ForgetPasswordModel
{
[Required]
[Display(Name = "Username")]
public string Username { get; set; }
}
View
#model MyFestival.Models.UserProfile
#{
ViewBag.Title = "Forgot Password";
}
<hr />
<div class="form-group">
<h3 class="panel-title">Did you forget your password?</h3>
</div>
#using (Html.BeginForm())
{
<div class="">
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, null, new { #style = "color:red;" })
<hr />
<label>To reset your password, input your email address and press the Reset Password button.</label>
<br/>
<div class="form-group" >
<div class="col-md-12" >
<div class="input-group">
<span class="input-group-addon" ><i class="glyphicon glyphicon-user" ></i ></span >
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control", #placeholder = "Username" })
</div >
#Html.ValidationMessageFor(m => m.UserName, null, new { #style = "color:red;" })
</div>
</div>
<br/>
<br/>
<div class="form-group" >
<div class="col-md-offset-2 col-md-10" >
<input type="submit" class="btn btn-default" value="Reset Password"/ >
#Html.ActionLink("Back to Login", "Login", null, new { #class = "btn btn-info" })
</div >
</div>
</div>
}
I've just spotted that you have both ForgetPasswordModel model and string username as arguments of your controller action and later you use Username property of your model. I assume that Model Binder just initializes the stirng username instead of ForgegPasswordModel. Could you try removing stirng username - the second parameter of ForgetPassword action?
You can create your own GUID and send it with email to user.
When user click on email link check Guid and update new password of user.
Here is the sample code
Create a view to enter forgot password email
#{
ViewBag.Title = "Forgot Password";
}
<h2>Forgot Password</h2>
#using (Html.BeginForm())
{
<div class="form-horizontal">
<hr />
<div class="text-success">
#ViewBag.Message
</div>
<div class="form-group">
Please enter your registered email address below to receive an email containing a link, to reset your password.
</div>
<div class="form-group">
<label class="control-label col-md-2">Email Address</label>
#Html.TextBox("EmailID", "", new { #class = "form-control" })
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Submit" class="btn btn-success" />
</div>
</div>
</div>
}
Then in your Controller get Email id from user, check if email exists and create new GUID, save it in database, send email to user.
[HttpPost]
public ActionResult ForgotPassword(string EmailID)
{
string resetCode = Guid.NewGuid().ToString();
var verifyUrl = "/Account/ResetPassword/" + resetCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);
//get user details from database.
using (var context = new LoginRegistrationInMVCEntities())
{
var getUser = (from s in context.RegisterUsers where s.Email == EmailID select s).FirstOrDefault();
if (getUser != null)
{
getUser.ResetPasswordCode = resetCode;
//This line I have added here to avoid confirm password not match issue , as we had added a confirm password property
context.Configuration.ValidateOnSaveEnabled = false;
context.SaveChanges();
var subject = "Password Reset Request";
var body = "Hi " + getUser.FirstName + ", <br/> You recently requested to reset your password for your account. Click the link below to reset it. " +
" <br/><br/><a href='" + link + "'>" + link + "</a> <br/><br/>" +
"If you did not request a password reset, please ignore this email or reply to let us know.<br/><br/> Thank you";
SendEmail(getUser.Email, body, subject);
ViewBag.Message = "Reset password link has been sent to your email id.";
}
else
{
ViewBag.Message = "User doesn't exists.";
return View();
}
}
return View();
}
private void SendEmail(string emailAddress, string body, string subject)
{
using (MailMessage mm = new MailMessage("youremail#gmail.com", emailAddress))
{
mm.Subject = subject;
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("youremail#gmail.com", "YourPassword");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
}
Now, when user click on the email and enter new password, check Guid with what we have saved in database and update password if guid matches.
Check for more info:
Forgot password functionality in ASP.NET MVC (Reset password by Email)