Trying to access html element in a view from controller in mvc - asp.net-mvc

I am trying to access html element of a view from Controller in asp.net Mvc.
In login form after filling data in username and password textbox. Posting it through Http Post and accessing it in controller and now based on condition in controller i want to manipulate html element in same view from where it is getting data.
view
<span id="spanInvalidCredentialsMessage" style="display:none">
<div class="row form-group">
<div class="col-md-8 col-md-offset-2 text-danger">
Your credentials could not be authenticated. Please try again.
</div>
</div>
<div class="row form-group">
<div class="col-md-8 col-md-offset-2">
<hr class="alert-danger" />
</div>
</div>
</span>
login form field in view
<div class="col-md-8 col-md-offset-2">
<span class="glyphicon glyphicon-user text-primary">
</span>Username
</div>
<div class="col-md-8 col-md-offset-2">
#Html.TextBox("txtBxUsername", null, new { #class = "form-control" })
#Html.TextBox("txtBxPassword", null, new { #class = "form-control" })
<input id="btnLogin" type="submit" value="Login" class="btn btn-primary btn-block" />
</div>
Controller section getting login details through httppost
[HttpPost]
public ActionResult Login(FormCollection form)
{
//Invoke the method to authenticate the user credentials. txtBxUsername.Text.Trim().ToUpper()
string msgUserAuthenticated=objADService.GenericIsAuthenticatedWithMessage("ABC", form["txtBxUsername"].ToString().Trim().ToUpper(),form["txtBxPassword"].ToString());
//Check if the user was authenticated.
if (msgUserAuthenticated.Equals("Authenticated", StringComparison.InvariantCultureIgnoreCase) == true)
{
//Set the Session Variable and Redirect to the Home Page ASPX.
Session[CommonConstants.SESSION_USER_ID] = form["txtBxUsername"].ToString().Trim().ToUpper();
Session[CommonConstants.SESSION_USER_DOMAIN] = form["txtBxPassword"].ToString();
//Redirect the user to the home page
//Response.Redirect("Home.aspx");
return View("Home");
}
else
{
//Show the error message.
spanInvalidCredentialsMessage.Visible = true;
//Clear the text boxes for Username and Password.
txtBxUsername.Text = "";
txtBxPassword.Text = "";
return View("Login");
}
}
Expected if wrong username & password would be there then in controller i can access html element id in view and display it.
actual
no idea how to achieve

Related

How can I return text to my current mvc view?

I have a login page within an ASP.NET Core App with a pop up to send a password reset email to the users email (Just using Identity):
<div class="login-body">
<div class="container">
<form asp-controller="Account" asp-action="Login" asp-route-returnurl="#ViewData["ReturnUrl"]" method="post" class="form-signin">
<h2 class="form-signin-heading">#Localizer["Sign In"]</h2>
<div class="login-wrap">
<div class="user-login-info">
<input asp-for="Email" type="email" class="form-control" placeholder="#Localizer["Email"]" autofocus/>
<span asp-validation-for="Email" class="text-danger"></span>
<input asp-for="Password" type="password" class="form-control" placeholder="#Localizer["Password"]"/>
<span asp-validation-for="Password" class="text-danger"></span>
</div>
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<label class="checkbox">
<input asp-for="RememberMe"/> Remember me
<span class="pull-right">
<a data-toggle="modal" href="#forgotPassModal">Reset Password</a>
</span>
</label>
<button class="btn btn-lg btn-login btn-block" type="submit">#Localizer["Sign In"]</button>
<div class="registration">
#Localizer["No Account"]
<a asp-area="" asp-controller="Account" asp-action="Register">#Localizer["Create Account"]</a>
</div>
</div>
<!-- Modal -->
<div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="forgotPassModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Reset Password</h4>
</div>
<div class="modal-body">
<p>Enter your e-mail address below to reset your password.</p>
<input type="text" name="email" placeholder="Email" autocomplete="off" class="form-control placeholder-no-fix">
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
<button class="btn btn-success" asp-controller="Account" asp-action="ForgotPassword" method="post">Submit</button>
#*<input type="button" class="btn btn-success" asp-controller="Account" asp-action="ForgotPassword" formmethod="post">Submit<input>*#
</div>
</div>
</div>
</div>
<!-- modal -->
</form>
</div>
When I input the email address it does the right thing, sends an email with a code, but it redirects me to a separate view stating to go check your emails.
Is it possible to just return a message either to the popup window or login page saying the same thing?
This is the ForgotPassword Action:
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByEmailAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user)))
{
return View("ForgotPasswordConfirmation");
}
var code = await UserManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.Action(nameof(ResetPassword), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Reset Password",
$"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>");
return View("ForgotPasswordConfirmation");
}
return View(model);
}
What you can use is TempData. TempData can hold data for one more additional request and only for one additional request. So you can store this information in the TempData. It is meant for things like your use case. It could look something like this.
public IActionResult Login()
{
var loginModel = new LoginModel();
loginModel.ForgotPassWordModel = (ForgotPassWordModel) TempData["ForgotPassword"];
return View(loginModel);
}
public IActionResult ForgotPassword()
{
if (valid)
{
TempData["ForgotPassword"] = new ForgotPassWordModel() {callbackUrl = "Go to this"};
return RedirectToAction("Login");
}
return View();
}
Here is my example LoginModel and my ForgottonPasswordModel. Ofcourse, yours will be more complicated.
public class ForgotPassWordModel
{
public string callbackUrl;
}
public class LoginModel
{
public ForgotPassWordModel ForgotPassWordModel { get; set; }
}
When someone makes a request to ForgotPassword, if it is valid, store the result in TempData and Redirect back to Login. Now you can read the TempData["ForgotPassword"] that you just set in the previous request. In my example, I put the data in my LoginModel. If there is no tempData, it would be null. Now in your view you can check for this ForgotPassword property.
#if (Model.ForgotPassWordModel != null)
{
// Show message/modal
}
The great thing about TempData is that when you set data, it is only held for one more additional request so it works for situations like these.

Prevent Modal Closing on form submit in Mvc

Is there a way to prevent the modal from closing when a form is submitted?
I am working on Email Sending Modal But When Click On Submit Button Controller Returns View, How To Prevent This ?
Modal Code Here:
#using (#Html.BeginForm("SendEmail", "Home", FormMethod.Post, new { #id = "form1", #enctype = "multipart/form-data" }))
{
<div class="form-group">
<div class="col-lg-offset-2 col-lg-10">
<span class="btn green fileinput-button">
<i class="fa fa-plus fa fa-white"></i>
<span >Attachment</span>
<input type="file" multiple="multiple" name="files" id="file">
</span>
<button class="btn btn-send" type="submit" >Send</button>
#ViewBag.Message
<br />
</div>
</div>
}
Here is Email Controller Code:
public ActionResult SendEmail(EmailContent emailContent, List<HttpPostedFileBase> files)
{
ViewBag.Message = "Email Sent Successfully!";
return RedirectToAction("Index","Home");
}
catch
{
ViewBag.Project = new SelectList(db.employees, "employee_id", "name");
ViewBag.Message = "Failed to Send Email, Please Try Again";
return RedirectToAction("Index","Home");
}
}
}
Please Help i want return no view , modal still open.

Cannot apply indexing with [] to an expression of type 'HttpRequest'

I am trying to get a value from a textbox of my View.
This is my View:
#model MyDataIndexViewModel
#{
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h1>Meine Daten</h1>
</div>
</div>
var item = Model.User;
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 myDataTitle">Email</div>
<div class="col-xs-6 col-sm-6 col-md-6">
#Html.TextBox("txtEmail", "", new { placeholder = item.Email})
</div>
</div>
}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<a class="btn btn-default pull-right" href="/ChangeMyData/Save">Speichern</a>
</div>
</div>
This is my Controller:
[HttpPost]
public ActionResult Save()
{
var email = Request["txtEmail"].ToString();
return View();
}
I get the error just as it says in the Title.
Thank you in advance!
VIEW:
#model MyDataIndexViewModel
#using (Html.BeginForm("Save", "CONTROLLER_NAME"))
{
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<h1>Meine Daten</h1>
</div>
</div>
var item = Model.User;
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6 myDataTitle">Email</div>
<div class="col-xs-6 col-sm-6 col-md-6">
#Html.TextBox("txtEmail", "", new { placeholder = item.Email, id="txtEmail"})
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<a class="submit btn btn-default pull-right">Speichern</a>
</div>
</div>
}
CONTROLLER
[HttpPost]
public ActionResult Save()
{
var email = Request.Form["txtEmail"].ToString();
return View();
}
You can either use strongly-typed viewmodel binding:
View
#model MyDataIndexViewModel
#* other stuff *#
#Html.TextBox("txtEmail", Model.Email)
Controller
[HttpPost]
public ActionResult Save(MyDataIndexViewModel model)
{
var email = model.Email;
return View();
}
Or use a TextBoxFor directly for model binding:
#model MyDataIndexViewModel
#* other stuff *#
#Html.TextBoxFor(model => model.Email)
Or if you still want to use HttpRequest members, Request.Form collection (a NameValueCollection) is available to retrieve text from txtEmail input:
[HttpPost]
public ActionResult Save()
{
var email = Request.Form["txtEmail"].ToString();
return View();
}
Note that Request["txtEmail"] is discouraged due to no compile time safety applied for it, because the key value may retrieved from Request.QueryString, Request.Form or other HttpRequestBase members.
Similar issue:
MVC TextBox with name specified not binding model on post
Access form data into controller using Request in ASP.NET MVC

How do I redirect from an MVC Post Action back to the bootstrap popup modal partial view where the post came from?

How do I redirect from an MVC Post Action back to the bootstrap popup modal partial view where the post came from?
Here is the PartialView sitting in the Bootstrap modal popup on the page.
It has a div with a validation taghelper waiting for any model errors.
#model CreateRoleViewModel
<div class="panel panel-primary partialModalFormDivs">
#Html.Partial("_ModalHeader",
new ModalHeader
{
Heading = "ADD ROLE",
glyphiconClass = "glyphicon glyphicon-random"
}
)
<div class="panel-body">
<div asp-validation-summary="All" class="text-danger"></div>
<form asp-action="CreateRole" method="post">
<div class="form-group">
<label asp-for="RoleName"></label>
<input asp-for="RoleName" class="form form-control" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Create</button>
<a asp-action="Index" class="btn btn-default">Cancel</a>
</div>
</form>
</div>
</div>
It posts to this action:
[HttpPost]
public async Task<IActionResult> CreateRole(CreateRoleViewModel createRoleViewModel)
{
if (ModelState.IsValid)
{
IdentityRole role = new IdentityRole(createRoleViewModel.RoleName);
IdentityResult result
= await _roleManager.CreateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index");
}
else
{
foreach (IdentityError error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
}
return View(createRoleViewModel);
}
I can return a PartialView like this at the end:
return View("_CreateRole", createRoleViewModel);
But then the whole page is cleared and this partial is returned with no layout file.
How can I return the results back to the modal popup window.
I understand the problem and the current behavior. But has anyone else solved this?
I think what you want to do is an ajax post and then just return a partial view and replace the form. The form should be inside a container div with an id that is used to replace its contents with the ajax post result. To do this you need to include the jquery unobtrusive ajax script which will auto wire the ajax based on the data-* attributes on the form as shown below
<div class="panel-body">
<div asp-validation-summary="All" class="text-danger"></div>
<div id="resultcontainer">
<form asp-action="CreateRole" method="post"
data-ajax="true"
data-ajax-method="POST"
data-ajax-mode="replace"
data-ajax-update="#resultcontainer"
>
<div class="form-group">
<label asp-for="RoleName"></label>
<input asp-for="RoleName" class="form form-control" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Create</button>
<a asp-action="Index" class="btn btn-default">Cancel</a>
</div>
</form>
</div>
</div>
and don't forget to return a partial view
return PartialView(createRoleViewModel);

Validation multiple checkbox form

in the page I have only three checkbox, the client should choose at least one before clicking on the submit button :
Controller :
[HttpPost]
public ActionResult Client(OrderItems model)
{
if (bValidated){
//Code here
}
else
{
model.itemChoosed = false;
return View("Client", model);
}
View Client :
#model WebApp.Models.OrderItems
#using (Html.BeginForm("Client", "Home", FormMethod.Post, new { #class = "form-group", role = "form" }))
{
#Html.AntiForgeryToken();
<h2>Client</h2>
#Html.Partial("SentMessage")
<div>
<div>
<h3>Item 1</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item1) Item 1</label>
</div>
<div>
<h3>Item 2</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item2) Item 2</label>
</div>
<div>
<h3>Item 3</h3>
<label>#Html.CheckBoxFor(model => model.CLInfo.Item3) Item 3</label>
</div>
</div>
<div class="row">
<input type="submit" name="action:Client" id="btnClient" class="btn btn-primary flat btn-large pull-right" value="Client" />
</div>
}
After I choose to put the condition into a Partail View :
Partial View SentMessage:
#model WebApp.Models.OrderItems
#if (!model.itemChoosed)
{
<div>You must choose at least one item</div>
}
I have the error message :
The view 'Client' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/Client.aspx
..
~/Views/Home/Client.cshtml
..
but Home/Client.cshtml existe since it's the view
Thanks

Resources