I want to create a login screen in which,on the click of button the ajax verify the password and then then submit the form.but when i click submit button the form is submitted before the ajax call
in short the action method and ajax both call on the same button click,but i want to call ajax before action method
View
#using (Html.BeginForm("Login", "AccountAP", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="login-box">
<div class="login-logo">
<!-- /.login-logo -->
<div class="login-box-body">
<center><img src="img/ra_logo.png" class="img-responsive" width="128" height="128" /></center>
<br />
<p class="login-box-msg" style="font-size:20px !important;">Sign in to start your session</p>
<div class="form-group has-feedback">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #placeholder = "Email" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
<div class="form-group has-feedback">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", #placeholder = "Password" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-12">
<input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>
</div>
<!-- /.col -->
</div>
</div>
<!-- /.login-box-body -->
</div>
</div>
}
<script type="text/javascript">
$('#btnSave').click(function (e) {
e.preventDefault();
e.alert("what's up");
});
</script>
I will suggest to capture the submit event on the form, instead of the click event on the submit button. Because people can not only submit your form by clicking the submit button, but also hitting the enter key in a textarea...etc
You will need to stop the default browser behavior of the submit event you capture so that whenever a for is submitted, browser won't post your form. In jQuery, you can stop default by doing event.preventDefault();
Check below code for that :
First Method :
#using (Html.BeginForm("Login", "AccountAP", FormMethod.Post,new { id= "submitForm" }))
{
<div class="col-xs-12">
<input type="submit" class="btn btn-primary pull-right btn-block btn-flat" value="Sign In" id="btnSave"/>
</div>
}
<script>
$(function () {
$("#btnSave").click(function(){
//Code for ajax verify the password then call below submitForm after validation
$("#submitForm").submit();
});
});
</script>
Second Method :
#using (Html.BeginForm("Login","AccountAP",FormMethod.Post, new { onsubmit = "myJsFunction()" }))
Your jquery code should be :
<script>
$(function () {
$("#btnSave").submit(function (event) {
event.preventDefault();
e.alert("what's up");
//Code for ajax verify the password then call below myJsFunction after validation
myJsFunction();
});
});
</script>
Related
Im trying to call the java script confirmation form submit but it skips it. It directly calls the controller even though i want to run first the java script for confirmation.
I dont know what im doing wrong. Still new to JV Scripts.
HTML
#model WMS_Web.Models.FileMaintenance.PrincipalModels
#section Scripts {
#Scripts.Render("~/Script/FileMaintenance/CommonFunction.js")
}
#{
ViewBag.Title = "PrincipalModel";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Principal</h2>
#using (Html.BeginForm("Create","Principal",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CompanyId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CompanyId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CompanyId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button onclick='functionConfirm("Do you like Football?", function yes() {
alert("Yes")
},
function no() {
alert("no")
});'>XXX</button>
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back", "ViewPrincipal")
</div>
Java Script
function functionConfirm(msg, myYes, myNo) {
var confirmBox = $("#confirm");
confirmBox.find(".message").text(msg);
confirmBox.find(".yes,.no").unbind().click(function () {
confirmBox.hide();
});
confirmBox.find(".yes").click(myYes);
confirmBox.find(".no").click(myNo);
confirmBox.show();
}
You can try this:
#using (Html.BeginForm("Create","Principal",FormMethod.Post))
{
#Html.AntiForgeryToken()
...
<input type="submit" name="name" value="Save" onclick="javascript: return SubmitForm();" />
}
Javascript:
function SubmitForm() {
var r = confirm("Are you sure you want to submit?");
if (r == false) {
return false;
}
// do something
return true;
}
I am creating a feedback form by FormMethod.Post method in mvc. Now, in my form data is saving but after save the data page is refreshed so that user cant know that data is successfully inserted or not. So, for thats why I want to alert the javascript and refresh the current page.
I have done many things but didnt work anything.
So, let I am showing you the last thing I tried that in this code.
Here is my view
<script>
#ViewBag.scripCall
function Callback() {
alert("Callback function is working");
}
</script>
#using (Html.BeginForm("Create", "FeedBack", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="container">
<div class="row">
<div class="col-sm-3">
<img src="~/images/default.png" style="margin:10px" height="200" width="200" id="imagePreview" />
<input type="file" name="ImageUpload" accept="image/jpeg, image/png" id="ImageUpload"
onchange="ShowImagePreview(this, document.getElementById('imagePreview'))" class="control-label" />
</div>
<div class="col-sm-2">
#Html.LabelFor(model => model.FullName, new { #class = "control-label" })
</div>
<div class="col-sm-8">
#Html.TextBoxFor(model => model.FullName, new { #class = "form-control", placeholder = "Enter The Name" })
</div>
<div class="col-sm-9">
<br />
</div>
<div class="col-sm-1">
#Html.LabelFor(model => model.Occupation, new { #class = "control-label" })
</div>
<div class="col-sm-8">
#Html.DropDownList("Occupation", ViewData["occupationList"] as SelectList, new {#class="control-label", style="width:250px;" })
</div>
<div class="col-sm-9">
<br />
</div>
<div class="col-sm-3">
#Html.LabelFor(model => model.UserFeedBack, new { #class = "control-label" })
</div>
<div class="col-sm-8">
#Html.TextBoxFor(model => model.UserFeedBack, new { #class = "form-control", placeholder = "Enter FeedBack", style="height:250px;" })
</div>
<div class="col-sm-3">
<input type="submit" id="btn_save" class="button" value="Save" />
</div>
</div>
<div class="row">
<span class="control-label" style="color:red">Note : Please do not upload <b>DSLR photo</b>. It does not support. Thank You...!!!</span>
</div>
</div>
}
Here is my controller
public ActionResult Create(FeedBackViewModel feedbackViewModel)
{
try
{
HttpPostedFileBase file = Request.Files["ImageUpload"];
if (file != null)
{
string fileName = Path.GetFileNameWithoutExtension(feedbackViewModel.ImageUpload.FileName);
string extension = Path.GetExtension(feedbackViewModel.ImageUpload.FileName);
fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
feedbackViewModel.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/images/"), fileName));
}
ContentRepository service = new ContentRepository();
int i = service.CreateFeedBack(file, feedbackViewModel);
if (i == 1)
{
ViewBag.scripCall = "Callback();";
return View();
//return Content("<script language='javascript' type='text/javascript'>alert('Thanks for Feedback!');</script>");
}
else
{
return Content("<script language='javascript' type='text/javascript'>alert('Sorry, Something went wrong. Please Try Again...!!!');</script>");
}
}
catch (Exception ex)
{
return View();//"Error", new HandleErrorInfo(ex, "StaffRegistration", "Create"));
}
}
Now, in this code the latest thing I triedto show the alert by #ViewBag.scripCall and also the refresh the current page but it also not working.
Thank You.
I am creating an ASP.NET MVC web application. In the form, the applicant can choose to add a co-applicant. If they choose to do so, elements of the co-applicant's information are required (ie, their first name, last name, email, etc.). I am using the jQuery Validate plugin to validate these text boxes.
Since the applicant does not need to include a co-applicant, I need to be able to the jQuery validate on these forms on and off. In other words, if the applicant chooses the button to add a co-applicant, the co-applicant information text boxes appear and these once hidden text boxes are now required.
Here is the code I tried to use, but it is not working.
HTML/MVC View:
<div class="form-group" id="coApplicantQuestion">
<p>Would you like to add another person to this application?</p>
<div class="col-md-10">
#Html.RadioButtonFor(e => e.CoAppFlag, false, new { id = "CoApplicantRadioNo", #checked = "checked" })
#Html.Label("CoApplicantRadioNo", "No")
<br />
#Html.RadioButtonFor(e => e.CoAppFlag, true, new { id = "CoApplicantRadioYes" })
#Html.Label("CoApplicantRadioYes", "Yes")
</div>
</div>
<div class="panel panel-default" id="coApplicantInfo">
<div class="panel-heading" role="button" data-toggle="collapse" data-target="#CoApplicantInfoToggle">Co-Applicant Information</div>
<div class="panel-body collapse in" id="CoApplicantInfoToggle">
<form id="coApplicantPersonalInfo">
<div class="form-group">
#Html.LabelFor(model => model.App2FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.App2FirstName, new { htmlAttributes = new { id = "coApplicantFirstName", #class = "form-control", Name = "coAppFirstName" } })
#Html.ValidationMessageFor(model => model.App2FirstName, "", new { #class = "text-danger" })
</div>
</div>
</form>
</div>
The jQuery Validate:
$(document).ready(function () {
$('#CoApplicantRadioYes input:radio').click(function () {
$('#coApplicantPersonalInfo').validate({
rules: {
coAppFirstName: {
required: true
}
},
onfocusout: function (element) { $(element).valid(); },
onkeyup: function (element) { $(element).valid(); }
});
});
});
The only time the jQuery Validate code works is when I take it out of the click() event, however, this will not work for my application since these text boxes are only required if there is a co-applicant.
How do I make this work? Is this even possible with jQuery validate?
The best choice is creating jq function for activating validation and other function for deactivating. Use syntax like:
$('#MyId').rules('remove', 'required');
and for adding use:
$('#MyId').rules('add', 'required');
When you show/hide controls based on the user's selection you can enable/disable those controls. Disabled controls are skipped during validation
$("#CoApplicantRadioYes").click(function(){
if($(this).is(":checked")){
$("#RequiredBasedOnCheckbox :input").removeAttr("disabled");
}
});
$("#CoApplicantRadioNo").click(function(){
if($(this).is(":checked")){
$("#RequiredBasedOnCheckbox :input").attr("disabled", "");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input id="CoApplicantRadioYes" type="radio" name="test" checked />
<input id="CoApplicantRadioNo" type="radio" name="test" />
<div id="RequiredBasedOnCheckbox">
<input type="text" required />
</div>
<button type="submit">Submit
</button>
</form>
I'm having following asp.net mvc 5 web application view page , Prevously its worked very well.
#model project_name.Models.SearchBrochureVM
#{
ViewBag.Title = "Brochure_Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Product Brochure Generation</h4>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group"></div>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Type, Model.TypeList, "Select the type", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Category, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Category, Model.CategoryList, "Select the category", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Category, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div>
</div>
<div class="row">
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Country, Model.CountryList, "Select the country", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Country, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
#Html.LabelFor(m => m.Product, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Product, Model.ProductList, "Select the subsidary", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Product, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button id="search" type="button" class="btn btn-success submit">Select Information</button>
</div>
</div>
</div>
}
<form id="brochureform">
<table class="table">
<thead>
<tr>
<th>Property_ID</th>
<th>IsChecked</th>
<th>Property Tile</th>
</tr>
</thead>
<tbody id="table"></tbody>
</table>
</form>
<table id="template" class="table" style="display: none;">
<tr>
<td>
<span></span>
<input type="hidden" name="[#].Property_ID" />
</td>
<td>
<input type="checkbox" name="[#].IsChecked" value="true"/>
<input type="hidden" name="[#].IsChecked" value="false"/>
</td>
<td>
<span></span>
</td>
</tr>
</table>
<div style="width:50%; float:left;text-align:left"><button id="resetborchure" type="button" class="btn btn-warning submit">Reset Brochure</button> </div>
<div style="width:50%; float:left;text-align:right"><button id="createborchure" type="button" class="btn btn-danger submit">Create Brochure</button> </div>
<script type="text/javascript">
</script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryui")
<script type="text/javascript">
var type = $('#Type');
var category = $('#Category');
var country = $('#Country');
var product = $('#Product');
$('#search').click(function () {
var url = '#Url.Action("FetchProductProperties")';
$.getJSON(url, { type: type.val(), category: category.val(), country: country.val(), product: product.val() }, function (data) {
$.each(data, function (index, item) {
var clone = $('#template').clone();
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
var cells = clone.find('td');
cells.eq(0).children('span').text(item.ID);
cells.eq(0).children('input').val(item.ID);
cells.eq(1).children('input').first().prop('checked', item.CheckOrNot)
cells.eq(2).children('span').text(item.Name);
$('#table').append(clone.find('tr'));
});
});
});
$('#createborchure').click(function () {
var data = $('#brochureform').serialize();
var url = '#Url.Action("Create_Brochure", "Brochure")';
//$.get(url, data, function (result) {
// window.location = url;
//});
$.ajax({
url: url,
type: 'GET',
data: data
})
.success(function (response) {
});
});
$('#resetborchure').click(function () {
table.empty();
});
</script>
}
Above view have two buttons called Reset Brochure and Create Brochure
Once I click Reset Brochure button its clear the table in that view and once I select Create Brochure its redirect to another view.
previously these two functions worked very well , but I cannot understand this isn't give any response once I click these buttons.
Since your wanting to redirect to another method (passing the values of the form controls in the table) there is no reason to use ajax, and instead you should just do a normal submit.
Replace the <form id="brochureform"> element with
#using (Html.BeginForm("Create_Brochure", "Brochure", FormMethod.Get))
{
<table class="table">
<thead>
....
</thead>
<tbody id="table"></tbody>
</table>
<input type="submit" value="CreateBrochure" />
}
and remove the <button id="createborchure" ...>Create Brochure</button> element and its associated script. This will now make a GET call to your public ActionResult Create_Brochure(IEnumerable<ProductsPropertiesVM> model) method
However this will also create a really ugly url and there is a risk that you will exceed the query string limit and throw an exception. In general GET methods should never have parameters which are collections.
From the DotNetFiddle you provided in chat, its unclear how your using the data you pass to the method (your create a variable string ids but then never actually use it. Assuming you do actually need it for the view you return in that method, I would suggest adding another POST method to avoid the issues above.
[HttpPost]
public ActionResult Initialize_Brochure(IEnumerable<ProductsPropertiesVM> model)
{
IEnumerable<int> selectedIDs = model.Where(x => x.IsChecked).Select(x => x.Property_ID);
string ids = string.Join(",", selectedIDs);
return RedirectToAction("Create_Brochure", new { id = ids });
}
and change the Create_Brochure() method to
public ActionResult Create_Brochure(string id)
{
....
}
and finally modify the BeginForm() to
#using (Html.BeginForm("Initialize_Brochure", "Brochure", FormMethod.Post))
This means you url will simply be something like
/Brochure/Initialize_Brochure/2,4,5 depending on the checkboxes you select
I have the following view
#using System.Linq;
#model MyCompanyNET.Models.ViewModels.AdministratorViewModel
<style type="text/css">
span {
padding-right: 10px;
}
...
</style>
<div class="manage">
<ul class="nav nav-tabs" id="myTab">
<li class="active">
<a data-toggle="tab" href="#invite">
<span class="glyphicon glyphicon-inbox"></span>Invite
</a>
</li>
...
</ul>
<div class="tab-content">
<div id="invite" class="tab-pane active fade in">
#Html.Partial("_InvitePartial", Model)
</div>
...
</div>
</div>
#section scripts {
<script>
$(function () {
$("input[type=button]").click(function () {
var data_email = $('#email').val();
var data_product = $('#product option:selected').text();
$.ajax({
url: '#Url.Action("SendInvite")',
type: 'POST',
data: { email: data_email, product: data_product },
success: function (result) {
$('#fail_message').html(result.result_failure);
$('#success_message').html(result.result_success);
}
});
});
});
</script>
}
The partial view is
#using (Html.BeginForm("SendInvite", "Tools", FormMethod.Post,
new
{
#class = "form-horizontal",
enctype = "multipart/form-data",
role = "form"
}))
{
#Html.AntiForgeryToken()
<h2>Invite Users</h2>
<div class="form-group">
#Html.LabelFor(m => m.EmailAddress, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.EmailAddress, new { #class = "form-control", id = "email" })
#Html.ValidationMessageFor(m => m.EmailAddress)
</div>
</div>
<div class="form-group">
#Html.Label("Access To", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("Product", new SelectList(
new List<Object> {
new { Text = "Product1", Value = "Product1" },
new { Text = "Product2", Value = "Product2" },
new { Text = "All", Value = "All" }},
"Value",
"Text"),
new { #class = "form-control", id = "product" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<span id="fail_message" class="label label-danger"></span>
<span id="success_message" class="label label-success"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="Invite User" class="btn btn-primary" />
</div>
</div>
}
and my controller is
[AllowAnonymous]
public async Task<JsonResult> SendInvite(string email, string product)
{
ApplicationUser user = null;
string result = String.Empty;
if (ModelState.IsValid)
{
if (String.IsNullOrEmpty(email))
{
return Json(new
{
result_success = String.Empty,
result_failure = "Please enter and email address"
}, JsonRequestBehavior.AllowGet);
}
}
... // Do stuff with email and product.
}
Now when this partial view code was in the view itself, everything worked fine. I'd get both the entered email address and the selected product coming through to my controller method SendInvite, but now the button does not even fire.
Now, I have changed the
<input type="button" value="Invite User" class="btn btn-primary"/>
to use submit
<input type="submit" value="Invite User" class="btn btn-primary"/>
This now calls my controller method but without the email parameter, which is always null(?). To make things worse, the return Json(new ... also does not render my <span id="success_message" class="label label-success"></span>s and it used to when everything was in the main view. Why is this occurring and how an I fix it?
Thank for your time.
the name of the email field is EmailAddress not email.. change your parameter name to string EmailAddress or you can change your markup to
#Html.TextBoxFor(m => m.EmailAddress, new { #class = "form-control", Name="email", id = "email" })
trick is the make the name of the field and your parameter name match, not the id.
Killercam, regarding your form submitting. Did you change it back to type="button" and not type="submit"? If not, reason is when you click the button, it will submit it and will disregard your JavaScript.
try decorating your action method by HttpPost