I have the following mvc login page that does not post to the controller.
LoginController
[HttpPost]
[AllowAnonymous]
public ActionResult Validate(AccountModels.LoginModel model)
{
if (!ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.RedirectFromLoginPage(model.UserName, model.RememberMe);
}
}
return View("Index");
}
cshtml
#using (Html.BeginForm("Validate", "Login", new { ReturnUrl = ViewBag.ReturnUrl, #class = "user" }, FormMethod.Post))
{
<div class="form-group">
#Html.TextBoxFor(u => u.UserName, new { placeholder = "Enter username", #class = "form-control form-control-user", #title = "Please enter your username.", required = "required", #id = "inputUserName"})
</div>
<div class="form-group">
#Html.PasswordFor(u => u.Password, new { placeholder = "Enter password", #class = "form-control form-control-user", #title = "Please enter your password.", required = "required", #id = "inputPassword" })
</div>
<div class="form-group">
<div class="custom-control custom-checkbox small">
<div class="form-check">
#Html.CheckBoxFor(u => Model.RememberMe, new {#class="form-check-input custom-control-input", #id = "formCheck-1"})
<label class="form-check-label custom-control-label" for="formCheck-1">Remember Me</label>
</div>
</div>
</div><button class="btn btn-primary btn-block text-white btn-user" type="submit">Login</button>
}
When I submit the form it does not enter the controller action "Validate", what could cause this?
Related
My Register.cshtml page contains both Patient and Doctor registration. I have written a script to check if the user is Patient then displays only information relevant to patient and vice-versa.
If click on register patient then patient information only should insert into the database and the vice-versa for doctor registration.
Currently, If I register patient then it should not take specialization data into database because it is doctor's specific information.
Another problem is that, If I change the specialization or city value from drop down then it throws error:
The ViewData item that has the key 'Specialization' is of type
'System.String' but must be of type 'IEnumerable'.
Exception Details: System.InvalidOperationException: The ViewData item
that has the key 'Specialization' is of type 'System.String' but must
be of type 'IEnumerable'.
Source Error: #Html.DropDownListFor(x
=> Model.Specialization, Model.Specializations, htmlAttributes: new { #class = "form-control form-control-sm" })
Register.cshtml
model Aayumitra.Models.RegisterViewModel
<!-- Register Form -->
<div id="accounts-form">
<div class="account-nav">
<div class="row">
<div class="col-md-12 text-center">
<ul class="d-flex align-items-center justify-content-center">
<li>#Html.ActionLink("Login", "Login", "Account", null, new { #class = "mr-4" })</li>
<li>#Html.ActionLink("Register", "Register", "Account", null, new { #class = "active" })</li>
</ul>
</div>
</div>
</div>
<script>
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
vars[key] = value;
});
return vars;
}
var text = getUrlVars()["profile"];
let profile;
if (text) {
if (text == 'doctor') {
profile = 'doctor';
}
if (text == 'patient') {
profile = 'patient';
}
} else {
profile = 'patient';
}
$(document).ready(function () {
if (profile === "doctor") {
$(".doctor").show();
}
else {
$(".doctor").hide();
}
});
</script>
<div class="container">
<div class="row py-5 border-top">
<div class="col-md-6">
<div class="form-img text-right">
<img src="~/Content/images/accounts.png" class="img-fluid" alt="Accounts Image">
</div>
</div>
<div class="col-md-5">
<div class="card">
<div id="form-card-header" class="card-header d-flex justify-content-between bg-white">
<h6>Join Aayumitra </h6>
<span class="float-right">Are you a Doctor? <span>#Html.ActionLink("register here", "register", "Account", new { profile = "doctor" }, null)</span>
</div>
<script>
var formCardHeader = document.getElementById('form-card-header');
if(profile == 'patient'){
formCardHeader.innerHTML = `
<h6>Join Aayumitra </h6>
<span class="float-right">Are you a Doctor? <span>#Html.ActionLink("register here", "register", "Account", new { profile="doctor"}, null)</</span>
`
}
if (profile == 'doctor'){
formCardHeader.innerHTML = `
<h6 id="join-doctors">Join 1000+ doctors</h6>
<span id="not-doctor" class=""text-primary>#Html.ActionLink("Not a doctor?", "register", "Account", new { profile="patient"}, null)</span>
`
}
</script>
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<div class="card-body">
<form action="register.chtml?profile=doctor">
<div class="form-group">
<label for="FullName">First Name</label>
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control form-control-sm", placeholder = "First Name" })
</div>
<div class="form-group">
<label for="FullName">Last Name</label>
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control form-control-sm", placeholder = "First Name" })
</div>
<div class="form-group">
<label for="email">Email</label>
#Html.TextBoxFor(m => m.Email, new { #class = "form-control form-control-sm", placeholder = "Email ID" })
</div>
<div class="form-group doctor">
<label for="number">Specialization</label>
#Html.DropDownListFor(x => Model.Specialization, Model.Specializations, htmlAttributes: new { #class = "form-control form-control-sm", placeholder = "Specialization" })
</div>
<div class="form-group">
<label for="number">City</label>
#Html.DropDownListFor(x => Model.City, Model.Cities, htmlAttributes: new { #class = "form-control form-control-sm", placeholder = "City" })
</div>
<div class="form-group">
<label for="number">Mobile Number</label>
<div class="col-md-8">
<div class="form-group">
#Html.TextBoxFor(m => m.MobileNumber, new { #class = "form-control form-control-sm", placeholder = "Mobile Number" })
</div>
</div>
</div>
<div class="form-group">
<label for="password">Create Password</label>
#Html.PasswordFor(m => m.Password, new { #class = "form-control form-control-sm", placeholder = "Password" })
</div>
<div class="form-group">
<input type="submit" value="Send" class="btn btn-primary btn-block">
</div>
</form>
</div>
}
</div>
</div>
</div>
</div>
</div>
<!-- Register Form End -->
Controller
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
var model = new RegisterViewModel();
List<SelectListItem> SpecialitiesList = GetSpecialities();
List<SelectListItem> CitiesList = GetCities();
model.Specializations = SpecialitiesList;
model.Cities = GetCities();
return View(model);
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email,FirstName=model.FirstName,LastName=model.LastName,City=model.City, IsDoctor = model.IsDoctor, NMC_Number = model.NMC_Number, Specialization = model.Specialization};
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);
}
I think the best way to solve it write two register action(doctor,Patient)that doctor and Patient have own view
I have a ajax.beginform that I have to upload a file and then in the view I have hidden for the path of the file that have been
saved in the server.
The problem is that the value of the path doesn't return to the view after the the post call.
I am returning new partial view with the errors and the value don't
coming
please help me
post method from controller that return partial view
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveSocioDetails(SpSocio socio) // ajax for 1 step in socio
{
bool sociook = false;
socio.StudentId = sStudentId; // bind student id to socio model
socio = SocioDetValid(ref sociook,socio);
// add validation
if (ModelState.IsValid && sociook)
{
socio = SaveSocioModel(socio);
Response.StatusCode = 200;
}
else
Response.StatusCode = 300; // return error to client the model is not valid
return PartialView("~/Views/Student/Socio/SocioDetails.cshtml", socio); // return the partial view of the forn with validation messages
}
Sociodetvalid function that saves the file and add the path to path field:
// bank account validation and save
if (socio.FileBankAccount == null) // if there is no file
{
if (socio.PathBankAccount == null) // check if he upload file already - if not add error message
{
ModelState.AddModelError("FileBankAccount", "חובה לצרף קובץ");
ok = false;
}
}
else // upload new the file
socio.PathBankAccount = Files.SaveFileInServer(socio.FileBankAccount, "BankAccount", sStudentId, socio.PathBankAccount);
the section in view for upload and the hidden for the path string:
<div class="row">
<div class="col-xl-3 col-lg-3 col-md-4 col-12 ">
#Html.LabelFor(model => model.BankStatus, htmlAttributes: new { #class = "control-label col-12" })
#Html.EditorFor(model => model.BankStatus, new { htmlAttributes = new { #class = "form-control must m-1 mt-0" } })
#Html.ValidationMessageFor(model => model.BankStatus, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.PathBankAccount)
</div>
<div class="col-xl-3 col-lg-3 col-md-4 col-12">
#Html.LabelFor(model => model.FileBankAccount, htmlAttributes: new { #class = "control-label col-12 must-sign", #for = "" })
<div class="chose-file m-1 mt-0">
#Html.TextBoxFor(model => model.FileBankAccount, new { #class = "form-control must", #type = "file", #accept = "image/jpeg,image/jpg,image/png,application/pdf", #style = "display:none;" })
<label for="FileBankAccount">
<i class="ml-1 material-icons">add_photo_alternate</i>
בחר קובץ
</label>
</div>
#Html.ValidationMessageFor(model => model.FileBankAccount, "", new { #class = "text-danger" })
</div>
#*
<div class="col-xl-3 col-lg-3 col-md-4 col-12" style="display:#(Model.PathBankAccount != null ? "" : "none")">
<label class="control-label col-12" for="">קובץ שמור</label>
<a name="#Model.PathBankAccount" class="btn btn-light btn-file m-1 mt-0">צפייה בקובץ שמור</a>
</div>*#
Thanks for help
Update:
Ajax form code : this is the part of the ajax that in a big view
<fieldset>
#using (Ajax.BeginForm("SaveSocioDetails", "Student", new AjaxOptions { HttpMethod = "POST", OnSuccess = "firstsuccess",OnFailure = "sociodetailsfail", UpdateTargetId="partialsocio" ,LoadingElementId = "div_loading" }, new { #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div id="partialsocio">
#Html.Action("PartialSocioDetails", "Student", new { SpId = ViewBag.SpId })
</div>
<div id="div_loading" style="display:none;">
<img src="#Url.Content("~/Content/Pic/Spinner.gif")" alt="" />
</div>
<button class="btn btn-primary" type="submit">המשך</button>
}
<input type="button" name="next" class="next action-button bg-primary" hidden value="Next" id="sociodetnext" />
</fieldset>
this is the function of fail and success ajax:
<script>
$(document).ready(function ()
{
});
function firstsuccess() {
console.log('this is ajaxSuccess');
$("#sociodetnext").click();
}
function sociodetailsfail(bdata) {
console.log('this is ajaxfail');
console.log(bdata.responseText);
$('#partialsocio').html(bdata.responseText);
}
</script>
In the script that Have returned to the client the value of the string doesn't appear..
Thanks for help
I'm having a Sign up form for the user to input : avatar, name, mail, etc...
The default image for the avatar is an user image, how can I update this image to be the new avatar that user pushes to the web?
Here's the SignUp view :
#model TimShop.Models.USERS
using (Html.BeginForm("SignUp", "Account", FormMethod.Post, new { #class = "login100-form validate-form signUpForm" }))
{
#Html.AntiForgeryToken()
<div class="container-login100">
<div class="wrap-login100 signUpPageFlex">
<div class="login100-pic js-tilt" data-tilt="" style="will-change: transform; transform: perspective(300px) rotateX(0deg) rotateY(0deg);">
<img src="~/Content/images/img-01.png" alt="avatar" class="signUpImg">
<input type="file" name="file" id="uploadAvatar" class="fileImgUpload">
<label for="uploadAvatar">
<i class="fa fa-upload"></i> Upload your avatar
</label>
</div>
<span class="login100-form-title signUpFormTitle">
Member resgiteration
</span>
<div class="wrap-input100 validate-input">
#Html.EditorFor(model=>model.FULLNAME, new { htmlAttributes = new { #class= "input100 SignUpInput", #required = "true", placeholder = "Full name", name= "fullname" } } )
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
#Html.EditorFor(model => model.EMAIL, new { htmlAttributes = new { #class = "input100 SignUpInput", #required = "true", placeholder = "Email", name = "email" } })
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
#*<input class="input100 SignUpInput" type="password" name="pass" placeholder="Password">*#
#Html.PasswordFor(model => model.PASS, new { htmlAttributes = new { #class = "input100 SignUpInput", #required = "true", placeholder = "Password", name = "pass" } } )
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
#Html.Password("confirmPass", new { htmlAttributes = new { #class = "input100 SignUpInput", #required = "true", placeholder = "Confirm password", name = "passConfirm" } })
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
#Html.EditorFor(model => model.DATEOFBIRTH, new { htmlAttributes = new { #class = "input100 SignUpInput", #required = "true", placeholder = "Date of birth", #type="date", name = "dob" } })
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input">
#Html.EditorFor(model=>model.PHONE, new { htmlAttributes = new { #class = "input100 SignUpInput", #required = "true", placeholder = "PHONE", #type = "number", name = "phone" } } )
<span class="focus-input100"></span>
</div>
<div class="container-login100-form-btn container-signUp-form">
<input class="login100-form-btn signUpbutton" type="submit" value="COMPLETE"/>
</div>
</div>
</div>
<!-- Body signUp end -->
}
And my controller that handles the sign up process:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SignUp([Bind(Include = "FULLNAME,PASS,EMAIL,DATEOFBIRTH,PHONE,AVATAR")] USERS user, string confirmPass, HttpPostedFileBase file)
{
bool error = false;
try
{
// TODO: Add insert logic here
if (db.USERS .Where(m => m.EMAIL == user.EMAIL).Any())
{
ViewData["insertResult"] = "This email is already taken.";
}
else
{
if(file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Content/images/users/") + file.FileName);
user.AVATAR= file.FileName;
}else
{
user.AVATAR = "";
}
db.USERS.Add(user);
db.SaveChanges();
Session["account"] = user.FULLNAME;
return RedirectToAction("Success", "Home", new { displayText = "Successful registeration" });
}
}
catch
{
ViewData["insertResult"] = "Cannot register your account. Please check again";
}
return View();
}
Or you can see the image that describes my idea to be clear :My idea
you have to write some javascript in your view code as below:
<script type="text/javascript">
function onChange(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#signUpImg').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#uploadAvatar").change(function(){
onChange(this);
});
Now change your view part image code as below:
<img src="~/Content/images/img-01.png" alt="avatar" id = "signUpImg" class="signUpImg">
Hope this will help you!
I am developing a basic web site in ASP.NET MVC 5 (using visual studio 2013). The site will use Facebook for user authentication and for retrieving initial profile data.like stack over flow login with facebook..access user name,profile photo etc..plz any one help me relevant sample
startup.auth.cs
FacebookAuthenticationOptions fbao = new FacebookAuthenticationOptions();
fbao.AppId = "****";
fbao.AppSecret = "*****";
fbao.Scope.Add("email");
fbao.Scope.Add("user_birthday");
fbao.Scope.Add("user_hometown");
fbao.SignInAsAuthenticationType = Microsoft.Owin.Security.AppBuilderSecurityExtensions.GetDefaultSignInAsAuthenticationType(app);
app.UseFacebookAuthentication(fbao);
Account controller>>Externallogincallback
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
ClaimsIdentity fboa = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
//var email = ext.Claims.First(x => x.Type.Contains("emailaddress")).Value;
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
Account view model
public class ExternalLoginConfirmationViewModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
public string UserName { get; set; }
}
externalloginconfirmationview
<h4>Association Form</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<p class="text-info">
You've successfully authenticated with <strong>#ViewBag.LoginProvider</strong>.
Please enter a user name for this site below and click the Register button to finish
logging in.
</p>
<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" })
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "text-danger" })
</div>
</div>
<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" })
#Html.ValidationMessageFor(m => m.UserName, "", new { #class = "text-danger" })
</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>
Following are some nice tutorials that may help solve your issue
http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
http://www.asp.net/mvc/overview/getting-started/aspnet-mvc-facebook-birthday-app
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);
}