ASP.Net MVC 5 Form in a Twitter Bootstrap Modal - Return to modal if user does not enter correct field information - asp.net-mvc

I have a contact form in a Twitter Bootstrap Modal and if the user happens to not enter a name or email address and hits submit I want to return to the Modal instead of just closing the Modal. Also if the form is valid I would like to let the user know that an we will be contacting them shortly in the same modal. Is this possible?
Here is my controler.
[HttpPost]
public ActionResult Index(Contact model)
{
ViewBag.IsValid = false;
ViewBag.CaptchaError = "";
RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
if (String.IsNullOrEmpty(recaptchaHelper.Response))
{
ViewBag.CaptchaError = "The Captcha cannot be empty";
return View();
}
RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
if (recaptchaResult != RecaptchaVerificationResult.Success)
{
ViewBag.CaptchaError = "The Captcha was incorrect";
return View();
}
if (ModelState.IsValid)
{
SendSupportEmail(model);
ViewBag.isValid = true;
}
return View();
}
Here is my view with the Modal
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content col-md-12">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Contact Us</h4>
</div>
<center>
<div class="modal-body">
#using (Html.BeginForm())
{
if ((bool)ViewBag.IsValid)
{
}
else
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Name, new { #class = "form-control", placeholder = "Name" })
#Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Phone, new { #class = "form-control", placeholder = "Phone" })
#Html.ValidationMessageFor(model => model.Phone)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", placeholder = "E-Mail Address" })
#Html.ValidationMessageFor(model => model.Email)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextAreaFor(model => model.Comments, new { #class = "form-control", height = "40", placeholder = "Comments" })
#Html.ValidationMessageFor(model => model.Comments)
</div>
</div>
<div class="form-group">
#if (!string.IsNullOrEmpty(ViewBag.CaptchaError))
{
<span class="field-validation-error">#ViewBag.CaptchaError</span>
}
#Html.Recaptcha(theme: Recaptcha.Web.RecaptchaTheme.Clean)
</div>
<div class="form-group">
<div class="col-md-12">
<input type="submit" id="submit" value="Submit" class="btn btn-default btn-lg btn-primary col-sm-12" />
</div>
</div>
</div>
}
}
</div>
</center>
</div>
</div>
I have searched everywhere and was unable to find a solution.

Don't have enough rep to comment - hence the answer. I reckon the easiest way to do this would be to use ajax. User jquery validation plugin to validate user input on submit click. This way, the validation messages can be displayed on the modal itself and the page doesn't have to be refreshed.
On successful validation, the form can be posted to your controller action. You can send a success message as part of your response and display it as a popup or a notification using notifyjs or your own code.

Related

bootstrap modal to appear when dropdownlist item is selected in mvc

I want a bootstrap modal with partial view to popup when a user selects the dropdownlist item.
For each selected item the popup should refresh with new content when the user selects a different item in the dropdownlist. From the code below, I could able to make the ajax and then redirect to partial view with model values but unable to display the modal popup
Index.cshtml
<div class="form-group">
#Html.LabelFor(model => model.SelectedIssue, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.DropDownListFor(model => model.SelectedIssue, Model.IssueDetails, "Please Select", new { #class = "form-control", #id = "IssueId" })
#Html.ValidationMessageFor(model => model.SelectedIssue, "", new { #class = "text-danger" })
</div>
</div>
$("#IssueId").change(function () {
$.ajax({
type: 'GET',
url: '#Url.Action("GetActionDetails")',
dataType: 'html',
data: { id: $("#IssueId").val() },
success: function (data) {
$('#modal-content').html(data);
$('#modal-container').modal('show');
},
error: function (ex) {
alert('Failed to retrieve action details' + ex);
}
});
return false;
});
The dropdown selection is making an ajax call and calling the below method in the controller
public ActionResult GetActionDetails(string id)
{
ActionDetails model = new ActionDetails();
model.ActionTaken = "Action Taken ";
model.AdviceGiven = "Advice Given to";
return PartialView("ActionDetails", model);
}
This is then redirecting to PartialView ActionDetails view which is below.
#model OnCallLogging.Models.ActionDetails
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 class="modal-title">Action Details</h3>
</div>
<div class="modal-body">
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(m => Model.ActionTaken, new { #class = "control-label col-sm-3"})
<div class="col-sm-9">
#Html.DisplayFor(m => m.ActionTaken, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => Model.AdviceGiven, new { #class = "control-label col-sm-3" })
<div class="col-sm-9">
#Html.DisplayFor(m => m.AdviceGiven, new { #class = "form-control" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-warning" data-dismiss="modal">Close</button>
</div>
And in the Layout.cshtml, the following markup is written before the body closing tag.
<div id="modal-container" class="modal fade hidden-print" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
</div>
and in the script.css
.modal-content {
width: 600px !important;
margin: 30px auto !important;
}
When I run the code, the screen goes dim but no popup appears. When I debug I could see ajax calling the controller action and redirecting to partial view, but the popup does not appear.
Not sure what am I missing to show the popup with model properties. Could anyone please help.
Since you are seeing the controller action being called while debugging, the harder part is working. The most likely explanation for your issue is in your javascript "success:":
//change from this:
$('#modal-content').html(data);
//to this:
$('.modal-content').html(data);
You can optionally, change your <div class="modal-content"> to <div id="modal-content">

How can i prevent page refresh (reload) while pressing login button in asp.net mvc identity?

So folks, i just created a _Login partial instead of Login view and rendered that partial view in my _Layout. The partial view is shown in a Modal, until yet everything seems OK! But whenever i just click the Login (Sign In) button the page reloads and nothing happens although i expect an error like the E-mail field cannot be empty or the user does not exist but surprisingly nothing happens and the page refreshes.
Here is the code for the _Login partial.
#model Hire.af.WebUI.Models.LoginViewModel
<div class="modal-body">
<!--Social Media Login Links-->
<div class="form-group row login-socical">
<div class="col-sm-9 col-sm-offset-3">
<div class="button_socical fb">
<i class="fa fa-facebook-square"> </i>
<em class="fa-facebook-square">Login with Facebook</em>
</div>
<div class="button_socical gg">
<i class="fa fa-google-plus"> </i>
<em class="fa-google-plus">Login with Google</em>
</div>
<div class="button_socical linkedin">
<i class="fa fa-linkedin-square"> </i>
<em class="fa-linkedin-square">Login with LinkedIn</em>
</div>
</div>
</div>
<!--Login Form-->
<form class="noo-ajax-login-form form-horizontal">
#using (Html.BeginForm("Login", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary(true, "", new { #class = "col-sm-3" })
<div class="form-group row">
#Html.LabelFor(m => m.Email, new { #class = "col-sm-3 control-label" })
<div class="col-sm-9">
#Html.TextBoxFor(m => m.Email, new { #class = "log form-control", #placeholder="Email OR Username" })
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
#Html.LabelFor(m => m.Password, new { #class = "col-sm-3 control-label" })
<div class="col-sm-9">
#Html.PasswordFor(m => m.Password, new { #class = "pwd form-control", #placeholder="Password" })
#Html.ValidationMessageFor(m => m.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<div class="checkbox">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
</div>
</div>
<!--Remember Me Checkbox-->
<div class="form-actions form-group text-center">
<button type="submit" class="btn btn-primary">Sign In</button>
<div class="login-form-links">
<span><i class="fa fa-question-circle"></i> Forgot Password?</span>
<span>
Don't have an account yet?
<a href="#" class="member-register-link" data-rel="registerModal">
#Html.ActionLink("Register Now", "Register") <i class="fa fa-long-arrow-right"></i>
</a>
</span>
</div>
</div>
#* Enable this once you have account confirmation enabled for password reset functionality
<p>
#Html.ActionLink("Forgot your password?", "ForgotPassword")
</p>*#
}
</form>
</div>
and below is how i rendered this partial in my _Layout.
<div class="memberModalLogin modal fade" id="userloginModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-member">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Login</h4>
</div>
<!--Login Partial Goes Here-->
#Html.Partial("_Login")
</div>
</div>
</div>
Any help would be appreciated.
You have nested forms which is invalid html and not supported. Remove the outer form from your partial view
<form class="noo-ajax-login-form form-horizontal"> // remove this and its closing tag
#using (Html.BeginForm(....

Why is my form validation not working when I have my validation summary in place

I have a #HTML.ValidationSummary within my form which is in a modal (dialog), however, it does not seem check if the form inputs have valid values before the modal closes. I will like the validation summary to be displayed, as shown below, my view model has validation attributes on it's properties.
#using (Html.BeginForm("Index", "Home", null, FormMethod.Post, new { Id = "frmSendEmail", #class = "form-horizontal" }))
{
<div class="modal fade" id="modalSendEmail" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalLabel">Email</h4>
</div>
<div class="modal-body">
#Html.ValidationSummary("Oops! Seems like we are missing some information, please provide details for the required field marked with a *", new { #class = "alert alert-danger" })
<div class="form-group">
<label for="txtName" class="col-sm-2 control-label">* Name:</label>
<div class="col-sm-10">
#Html.TextBoxFor(model => model.SenderName, null, new {id = "txtName", #class = "form-control", placeholder = "Name"})
#Html.ValidationMessageFor(model => model.SenderName)
</div>
</div>
<div class="form-group">
<label for="txtEmail" class="col-sm-2 control-label">* Email:</label>
<div class="col-sm-10">
#Html.TextBoxFor(model => model.SenderEmail, null, new { id = "txtEmail", #class = "form-control", placeholder = "Email", type = "email" })
#Html.ValidationMessageFor(model => model.SenderEmail)
</div>
</div>
<div class="form-group">
<label for="txtTelephone" class="col-sm-2 control-label">Telephone:</label>
<div class="col-sm-10">
#Html.TextBox("telephone", null, new { id = "txtTelephone", #class = "form-control", placeholder = "Telephone" })
</div>
</div>
<div class="form-group">
<label for="txtEnquiry" class="col-sm-2 control-label">* Enquiry:</label>
<div class="col-sm-10">
#Html.TextAreaFor(model => model.SenderEnquiry, new { id = "txtEnquiry", #class = "form-control", rows = "5" })
#Html.ValidationMessageFor(model => model.SenderEnquiry)
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-warning" id="btnSendEmail">Send</button>
</div>
</div>
</div>
</div>
}
**Model**
public class Enquiry
{
[Required]
public string SenderName { get; set; }
[Required]
public string SenderEmail { get; set; }
public string SenderTelephone { get; set; }
[Required]
public string SenderEnquiry { get; set; }
}
In the View, change
#Html.ValidationSummary("Oops! Seems like we are missing some information, please provide details for the required field marked with a *", new { #class = "alert alert-danger" })
to
#Html.ValidationSummary(true, "", new { #class = "alert alert-danger" })
In the controller:
public ActionResult Index(Enquiry emailEnquiry)
{
if (ModelState.IsValid)
{
// all done
return ...
}
ModelState.AddModelError("", "Something is invalid.");
return View(emailEnquiry); // don't forget returning with model
}

How can I write a submit form using bootstrap modal?

I'm using a bootstrap modal in asp.net mvc 5. But I'm having a problem with modal which I can't submit data. I have had call a _regiserPartial View form my _Layout (Master Page).
my controller:
[HttpPost]
public ActionResult Register(UserViewModel model)
{
var userViewModel = Mapper.Map<UserViewModel, User>(model);
if (ModelState.IsValid)
{
userViewModel.Status = true;
_userService.InsertUser(userViewModel);
model = new UserViewModel();
}
return View(model);
}
my _registerPrtial View:
#model HoiCode.Web.Models.Users.UserViewModel
<form class="form-horizontal">
<div id="registerModal" 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">Resgister</h4>
</div>
#using (Html.BeginForm("Register", "User", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="modal-body">
<div class="form-group">
<label class="col-sm-4 control-label">#Html.LabelFor(m => m.Email)</label>
<div class="col-sm-8">
#Html.TextBoxFor(m => m.Email, new { #type = "email", #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label">#Html.LabelFor(m => m.Password)</label>
<div class="col-sm-8">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
}
</div>
</div>
</div>
<script>
$(document).ready(function () {
$('.launchRegisterModal').click(function () {
$('#registerModal').modal({
keyboard: false
});
});
});
</script>
my _layout: I'll call _registerPartial from here
Register

how to launch Bootstrap Modal as sign in with validatoin?

I have a login modal which is a partial view, then i can pop up window for user to login in anytime.below is how it looks like.
#model LeduInfo.Models.LoginModel
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<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" id="myModalLabel"> Login </h4>
</div>
<div class="container">
<div class="modal-body">
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { #id="signinForm"}))
{
#Html.ValidationSummary(true, "Account creation was unsuccessful. Please correct the errors and try again.")
<div class="control-group">
<label class="control-label" for="inputEmail">User Name</label>
<div class="controls">
#Html.TextBoxFor(m => m.UserName, new { #name = "inputUser", #class = "form-control", #id = "inputUser", #placeholder = "User Name" })
#Html.ValidationMessageFor(m=>m.UserName)
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
#Html.TextBoxFor(m => m.Password, new { #name = "inputPassword", #class = "form-control", #id = "inputPassword", #placeholder = "Password", #type = "password" })
#Html.ValidationMessageFor(m=>m.Password)
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
Remember me #Html.CheckBoxFor(m => m.RememberMe)
<span class="span9"> #Html.ActionLink("Register", "Register", "Account") </span>
</label>
<button type="button" id="submit_btn" class="btn btn-primary" >sign in</button>
</div>
</div>
}
</div>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
but now, i fount it will submit form when click on sign in button and window closed, that is not what i wanted, then i add jquery code as below to manually submit form. but if in this case, then i can not got info return from server for validation, how can i fix it with submit form but not close modal?
<script type="text/javascript">
// Setup form validation on the #register-form element
$('#submit_btn').click(function () {
var form = $('#singinForm');
$("#signinForm").validate({
// Specify the validation rules
rules: {
inputUser: "required",
password: {
required: true,
minlength: 6
}
},
// Specify the validation error messages
messages: {
inputUser: "Please enter your first name",
password: {
required: "Please provide a password",
minlength: "Your password must be at least {0} characters long"
},
},
submitHandler: function (form) {
form.submit();
$('#signinForm').find("#submit_btn").attr("disabled", true).attr("value", "Submitting...");
}
});
}
});

Resources