Ajax script not working on Form Submit? - javascript

I have an issue, I am loading a partial page however I dont want the form on this page to redirect when I click the save button.
Not sure if I am using the script the correct way, I want to Post to the controller when I click submit but I want to be redirected back to the same page I was on (AdminPanel/AdminProfile) and not redirected to a different controller/view (Account/Manage).
AdminProfile View:
<div id="tab-2" class="tab-pane">
#{Html.RenderPartial("~/Views/Account/Manage.cshtml");
}
</div>
Not sure if my script should go in this view or stay in the partial view?
Controller:
public ActionResult Manage(LocalPasswordModel model)
{
//....
return Json(new { redirectTo = Url.Action("AdminProfile", "AdminPanel") });
}
Partialview with script:
#model LocalPasswordModel
#{
ViewBag.Title = "Change Password";
}
<section class="hgroup">
<div class="panel-body">
<ul class="breadcrumb pull-right top-right">
<li>You're logged in as <strong>#User.Identity.Name</strong></li>
</ul>
<ul class="message-success">#ViewBag.StatusMessage</ul>
#using (Html.BeginForm("Manage", "Account", FormMethod.Post, new { id = "SavePassword", #class = "form-horizontal" }))
{
<div class="social_sign">
<h3>Change your password.</h3>
</div>
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
<label class="col-sm-2 control-label">Old Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.OldPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">New Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.NewPassword, new { #class = "form-control"})
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-sm-12 col">
<input type="submit" class="btn btn-primary pull-right" value="Change password" />
</div>
</div>
}
</div>
</section>
Script in the view above:
#section Scripts {
<script>
$('#SavePassword').submit(function ()
{
if ($(this).valid())
{
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result)
{
if (result.redirectTo)
{
window.location.href = result.redirectTo;
}
else
{
$(".tab-2").html(result);
}
},
error: function ()
{
}
});
}
})
</script>
#Scripts.Render("~/bundles/jqueryval")
}
Nothing seems to happen all I get is an empty page with {"redirectTo":"/AdminPanel/AdminProfile"} in it. Which is the url: http://localhost:57239/Account/Manage

you should change your code like these:
<script>
$('#SavePassword').submit(function ()
{
if ($(this).valid())
{
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result)
{
if (result.redirectTo)
{
window.location.href = result.redirectTo;
}
else
{
$(".tab-2").html(result);
}
},
error: function ()
{
}
});
}
return false;
})
</script>

You have already attached the AJAX call, but forgot to prevent the default submission event. So, use event.preventDefault():
$('#SavePassword').submit(function (e) {
e.preventDefault();
// Rest of your code.
if ($(this).valid())

Related

Disabling Button After First Click Ajax.BeginForm with Javascript

Having an issue hiding/disabling the submit button with it also submitting the form. I have tried adding: onclick="this.value='Submitting, Please Wait.'; this.disabled='disabled';" into the input submit field which will disable the button but wont submit the form. I have tried placing this into the javascript portion also and it not working. I have tried things like this also:
$("#SignInButton").one('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true);
});
I am at a loss because a lot of examples I am looking at are for html.beginform and this old form was set up with Ajax.BeginForm. Any insight on how to either just hide the button or disable the button with the code below would be much help!!
<div id="LoginModal" style="display:none;padding:1rem;max-width:580px;">
#using (Ajax.BeginForm("Login", "Accounts",
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnFailure = "OnSuccess"
}))
{
<div>
Other Form Data
<div>
#Html.Hidden("ItemID", Model.ItemID)
<input type="submit" id="SignInButton" data-loading-text="Signing in" class="button success" value="Sign In" />
</div>
</div>
}
<script type="text/javascript">
var ready;
ready = function () {
$(".fancybox").fancybox({
'content': $('#LoginModal'),
'onStart': function () { $("#LoginModal").css("display", "block"); },
'onClosed': function () { $("#LoginModal").css("display", "none"); }
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
</script>
EDIT!!!!!
<div id="LoginModal" style="display:none;padding:1rem;max-width:580px;">
#using (Ajax.BeginForm("Login", "Accounts", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnSuccess" }))
{
<h1>Sign In</h1>
var displayLocalLogin = "";
#Html.AntiForgeryToken()
#Html.ValidationSummary(false, "", new { #class = "text-error" })
#Html.Sitecore().FormHandler()
<div class="">
<div class="row">
<div class="internal">
<div class="medium-12 columns">
</div>
<div class="medium-12 border-top columns">
<div class="form-group">
<label for="UserName">UserName <span class="required">*</span></label>
#Html.TextBoxFor(m => m.UserName)
#Html.ValidationMessageFor(m => m.UserName)
</div>
</div>
<div class="medium-12 columns">
<div class="form-group">
<label for="Password">Password <span class="required">*</span></label>
#Html.PasswordFor(m => m.Password)
#Html.ValidationMessageFor(m => m.Password)
</div>
</div>
<div class="medium-12 columns" style="padding-bottom: 10px;">
<div class="form-group">
</div>
</div>
<div class="medium-5 columns left">
<div class="form-group">
<div>
<div>
#Html.Hidden("ItemID", Model.ItemID)
<input type="submit" id="SignInButton" data-loading-text="Signing in" class="button success" value="Sign In">
</div>
</div>
</div>
</div>
</div>
#if (string.Equals(System.Configuration.ConfigurationManager.AppSettings["EnableSalesForceLogin"], "true", StringComparison.InvariantCultureIgnoreCase))
{
displayLocalLogin = "displaynone";
#Html.Partial("/salesforceloginpartial.cshtml")
}
</div>
</div>
}
<script type="text/javascript">
$("#SignInButton").one('click', function (event) {
$(this).prop('disabled', 'disabled');
});
//function OnSuccess(data) {
// alert(data);
// $('#LoginModal').parent.html(data).css("display", "block");
// $("#LoginModal").css("display", "block");
//}
var ready;
ready = function () {
$(".fancybox").fancybox({
'content': $('#LoginModal'),
'onStart': function () { $("#LoginModal").css("display", "block"); },
'onClosed': function () { $("#LoginModal").css("display", "none"); }
});
};
$(document).ready(ready);
$(document).on('page:load', ready);
</script>
You can disable the button in the next event loop excecution by using setTimeout(func, 0):
$("#SignInButton").one('click', function (event) {
setTimeout(function() {
event.preventDefault();
$(this).prop('disabled', true);
}, 0);
});
This will block the button right after the user click, but it will pass the first click.
I think you should set the attribute disabled to "disabled" instead
$(this).prop('disabled', 'disabled');
You can probably try to make use of ajaxStart and ajaxStop methods from jquery.
http://api.jquery.com/ajaxStart/
http://api.jquery.com/ajaxStop/
May be something like, in ajaxStart disable the button.
You need to submit the form after disabling button.
Give to your form an id:
#using (Ajax.BeginForm("Login",
"Accounts",
new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnFailure = "OnSuccess" },
new { id = "formId"}))
and then submit it by javascript:
$("#SignInButton").one('click', function (event) {
event.preventDefault();
$(this).prop('disabled', true); //disable button
$("#formId").submit(); //submit the form
});

Disable button once its being clicked on after Ajax - ASP.NET MVC5

I have a form in ASP.NET MVC5 that uses FormMethod.Post I have a Create button that submits the form, but how would I get it to work so that if you click Create then it disables the button. I have tried:
onclick="this.disabled = true"
But then the form is not submitted, hower when it is removed it allows you to add multiple records when clicking Create
This is my code for the form:
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript" type="text/javascript">
// cancel
$(document).on("click",
"#CancelForm",
function(e) {
var uri = '#Html.Raw(Url.Action("Index", "Membership"))';
window.location = uri;
e.preventDefault();
});
// submit
$(document).on("click", "#submitMembership", function(e) {
// Perform Ajax request to check if CAE/IPI Number is unique.
var caeipinumber = $('#addMembershipCAEIPINumber').val();
if (caeipinumber) {
$.ajax({
url: '#Url.Action("IsCAEIPINumberUnique", "Membership")',
data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
type: 'POST',
async: false,
cache: false,
success: function(result) {
if (result.toLowerCase() == "false") {
// Number is not unique and already exists, so display validation error to the user.
e.preventDefault();
$('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
return false;
}
return true;
},
error: function(xhr, status, error) {
}
});
}
});
</script>
}
#section additionalStyles {
}
#section modal {
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-1"></div>
<div id="createMembership" class="col-md-10 formContainer">
<div class="panel">
<div class="panel-heading">
<span class="panel-title">
<i class="glyphicon glyphicon-pencil"></i> Details of New Membership
</span>
</div>
#using (Html.BeginForm("AddMembership", "Membership", FormMethod.Post, new { id = "addMembershipForm", role = "form", #class = "theme-primary form-horizontal" }))
{
<fieldset>
<legend style="display: none">Add Membership Form</legend>
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="panel-body p25 fill bt0 pbn">
<div class="form-group">
#Html.LabelFor(x => x.MembershipName, new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.TextBoxFor(x => x.MembershipName, new { id = "addMembershipName", #class = "form-control", placeholder = "Enter Membership Name..." })
#Html.ValidationMessageFor(x => x.MembershipName, string.Empty, new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.CAEIPINumber, new { #class = "control-label col-md-3" })
<div class="col-md-8">
#Html.TextBoxFor(x => x.CAEIPINumber, new { id = "addMembershipCAEIPINumber", #class = "form-control", placeholder = "Enter CAE / IPI Number..." })
#Html.ValidationMessageFor(x => x.CAEIPINumber, string.Empty, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="text-center">
<input type="button" class="btn btn-primary" id="CancelForm" value="Cancel" />
<input id="submitMembership" type="submit" class="btn btn-primary" value="Create" />
</div>
</div>
</fieldset>
}
</div>
</div>
<div class="col-md-1"></div>
</article>
You should listen the form submit event, the submit input used trigger the form submit event and when the event is triggered you can disable the Button you clicked.
$("#form1").submit(function (){
$("#submitbtn").prop ("disabled",true);
$.ajax({requestprops,success:function(){
$("#submitbtn").prop ("disabled",false);
}});
});
This should work:
<script>
function setDisable(id) {
document.getElementById(id).disabled=true;
};
</script>
<input id="submitMembership" type="submit" onclick="setDisable(this.id)" class="btn btn-primary" value="Create" />
First, I would remove the binding on the click of the submit button and instead bind on the submit event.
Replace your submit button function with the following:
$("#addMembershipForm").submit(function (e) {
var submitButton = $(this).find(':input[type=submit]').prop('disabled', true); // Find and disable the submit button
// Perform Ajax request to check if CAE/IPI Number is unique.
var caeipinumber = $('#addMembershipCAEIPINumber').val();
if (caeipinumber) {
$.ajax({
url: '#Url.Action("IsCAEIPINumberUnique", "Membership")',
data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
type: 'POST',
async: false,
cache: false,
success: function(result) {
if (result.toLowerCase() == "false") {
// Number is not unique and already exists, so display validation error to the user.
submitButton.prop('disabled', false); // Enable submit button
e.preventDefault(); // Do not submit form
$('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
}
},
error: function(xhr, status, error) {
}
});
}
});
var submitButton = $(this).find(':input[type=submit]').prop('disabled', true);is used to find and then disable the button.
It will then do your unique check the same as you had in your original question. However, we will enable the submit button if it returns false so the user can re-submit.

Why doesn't the ajax post data to the controller?

I have been trying to send data to a controller using ajax but it redirects me to another url instead of posting data into the controller.
#section CustomScripts
{
<script type="text/javascript">
function save() {
var BookingDetails =
{
VehicleModel: document.getElementById('VehicleModel').value,
VehicleRegNo: document.getElementById('VehicleRegNo').value,
AppointmentTime: '1',
CustomerName: document.getElementById('CustomerName').value,
ContactNo: document.getElementById('ContactNo').value
}
var bd = JSON.stringify(BookingDetails);
$.ajax
({
url: '#Url.Action("Appointment", "AddAppointment")',
type: 'POST',
contentType: "application/json; charset= utf-8",
data: bd,
dataType: 'json',
success: function (results) {
#*window.location = '#Url.Action("Appointment", "AddAppointment")';*#
}
});
}
</script>
}
Controller:
[HttpPost]
public ActionResult AddAppointment(AddBookingsViewModel AddBookingVM)
{
BookingsRepository BookingRep = new BookingsRepository();
int ReturnRowsCount = BookingRep.InsertCustomerAppointments(AddBookingVM, out ReturnStatus, out ReturnMessage);
if (ReturnRowsCount > 0)
{
//ShowMessage(MessageBox.Success, OperationType.Saved, ReturnMessage);
ViewBag.Message = ReturnMessage;
return RedirectToAction("AddAppointment", "Appointment");
}
else
{
ShowMessage(MessageBox.Error, OperationType.Error, ReturnMessage);
}
return View(AddBookingVM);
}
I have using a input with type submit which is calling save(); on onclick event.
<input type="submit" onclick="save();" class="btn btn-default pull-right" value="Book Now"/>
Here is the full view code:
#model ZahidCarWash.ViewModels.AddBookingsViewModel
#{
ViewBag.Title = "Add Appointment";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<!-- page banner -->
<div id="page-banner" class="page-banner-main" style="background-image: url('Content/images/bg/page-banner.jpg')">
<div class="container">
<div class="page-banner-block">
<div class="section">
<h3 class="section-heading">Appointments</h3>
</div>
<ol class="breadcrumb">
<li>Home</li>
<li>Page</li>
<li class="active"><a>Appointments</a></li>
</ol>
</div>
</div>
</div>
<!-- end page banner -->
#*#using (Html.BeginForm("AddAppointment", "Appointment", FormMethod.Post, new { enctype = "multipart/form-data" }))
{*#
<!-- appointments -->
<div id="appointments" class="appointment-main-block appointment-two-main-block">
<div class="container">
<div class="row">
<div class="section text-center">
<h3 class="section-heading text-center">Get an Appointment</h3>
#*<p class="sub-heading text-center">Etiam imperdiet imperdiet orci nunc nec neque phasellus leo dolor tempus non auctor.</p>*#
</div>
<div class="col-md-4 hidden-sm">
<div class="appointment-img">
<img src="~/Content/images/appointment.jpg" class="img-responsive" alt="Appointment">
</div>
</div>
<div class="col-md-8 col-sm-12">
<div class="appointment-block">
<form id="appointment-form" class="appointment-form" method="post" action="https://mediacity.co.in/autoplus/car-wash/version1/appointment.php">
<h5 class="form-heading-title"><span class="form-heading-no">1.</span>Vehicle Information</h5>
<div class="row">
<div class="col-sm-4">
<div class="dropdown">
#Html.DropDownListFor(Model => Model.fk_VehicleMakeID, new SelectList(ZahidCarWash.DAL.VehicleMakesRepository.getVehicleMakes(), "VehicleMakeID", "MakeTitle"),
new { #class = "form-control" })
</div>
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.VehicleModel, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Vehicle Model" } } )
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.VehicleRegNo, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Vehicle Reg No." } })
</div>
</div>
<h5 class="form-heading-title"><span class="form-heading-no">2.</span>Available Timings</h5>
<div class="row">
#*<div class="col-sm-6">
<input type="text" class="form-control date-pick" id="appointment-date" name="appointment-date" placeholder="Appointment Date" required>
</div>*#
<div class="col-sm-6">
<div class="dropdown">
#Html.DropDownListFor(Model => Model.fk_TimeSlotID, new SelectList(ZahidCarWash.DAL.TimeSlotsRepository.getTimeSlots(), "TimeSlotID", "FromTo"), new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.fk_TimeSlotID, "", new { #class = "ErrorMessages" })
</div>
</div>
</div>
<h5 class="form-heading-title"><span class="form-heading-no">3.</span>Contact Details</h5>
<div class="row">
<div class="col-sm-4">
#Html.EditorFor(Model => Model.CustomerName, new { htmlAttributes = new { #class = "form-control", placeholder = "Customer Name" } })
#Html.ValidationMessageFor(Model => Model.CustomerName, "", new { #class = "ErrorMessages" })
</div>
<div class="col-sm-4">
#Html.EditorFor(Model => Model.ContactNo, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Contact Number." } })
#Html.ValidationMessageFor(Model => Model.ContactNo, "", new { #class = "ErrorMessages" })
</div>
#*<div class="col-sm-12">
<textarea id="message" name="message" rows="6" placeholder="Message"></textarea>
</div>*#
</div>
<input type="submit" onclick="save();" class="btn btn-default pull-right" value="Book Now"/>
</form>
</div>
</div>
</div>
</div>
</div>
As discussed, change the type of your button to be a "button". Remove the onclick attribute and add an "id". We'll use this id to capture the button click.
<input type="button" id="btnSubmit" class="btn btn-default pull-right" value="Book Now"/>
Change the form declaration to the below. Looks like you have it commented out!
#using (Html.BeginForm("", "", FormMethod.Post, new { id = "frmMyForm" }))
{
//HTML here
}
Capture the click in Jquery, serialize the form and post the form to the controller.
$(document).on("click", "#btnSubmit", function () {
var data = $("#frmMyForm").serialize();
$.ajax({
async: true,
type: "POST",
data: data,
url: "/Appointment/AddAppointment/",
success: function () {
//Do stuff here if needed
},
complete: function () {
//Stuff here if needed
}
});
});
Hope that helps you on your way,
You have url: '#Url.Action("Appointment", "AddAppointment")', but your Controller Action name is: public ActionResult AddAppointment(AddBookingsViewModel AddBookingVM)
(updated)
But you also have a RedirectToAction in your Action for the $.ajax - the $.ajax should have a response.
Try just sending a HttpPost transaction by changing your script to this:
function save() {
var BookingDetails =
{
VehicleModel: document.getElementById('VehicleModel').value,
VehicleRegNo: document.getElementById('VehicleRegNo').value,
AppointmentTime: '1',
CustomerName: document.getElementById('CustomerName').value,
ContactNo: document.getElementById('ContactNo').value
}
var form = document.createElement("form");
var url = '#Url.Action("Appointment", "AddAppointment")';
form.setAttribute("method", "POST");
form.setAttribute("action", url);
for (var key in BookingDetails) {
if (data.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", data[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
form.remove();
}
This is a straight HttpPost with no return expected in the script. It creates a form, attaches the data (by creating hidden inputs) to be sent to the action, adds the form to the DOM, submits and then removes it.

Call JS method from Razor form submit

When I submit the form I want to fire-up the Javascript method written below. This JS method will send a POST request to the backend. However, in the code written below this JS method is not being fired. Can someone please help me how to correct this ?
#using (Html.BeginForm(null, null, FormMethod.Post, new { #class = "form-horizontal", onsubmit = "submitdata" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<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 {id ="Email", #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.pwd, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.pwd, new {id="pwd", #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">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" onsubmit="submitdata"/>
</div>
</div>
}
Javascript
function submitdata() {
var pwd = document.getElementById("pwd");
var email = document.getElementById("email");
$.ajax({
type: 'post',
url: '/Account/Reg',
data: {
email: email,
password: pwd
},
success: function (response) {
$('#success__para').html("You data will be saved");
}
});
return false;
}
You miss () in your onsubmit attribute;
onsubmit = "submitdata()"
As Vostrugin mentioned in his answer, you are missing () in the method call.
Here is the unobtrusive javascript way (using jQuery)
function submitdata() {
// your existing code
}
$(function(){
$("form").submit(function(e){
e.preventDefault();
submitData();
});
});
If you want to wire it with a specific button click, use a jQuery selector to get the button and bind the click event.
<input type="submit" id="myButton" value="Register"/>
and
$(function(){
$("#myButton").click(function(e){
e.preventDefault();
submitData();
});
});
With this approach, you should remove the onsubmit event from your UI markup.

Form serialization always returns empty string

I have a dropdown in my view. Based on the selection, i insert a partial view into a div (placeholder) in view. Below is the View.
<div class="container">
<div class="row">
<div class="col-lg-4"><p class="lead">What do you want to do?</p></div>
<div class="col-lg-8">
<select id="myDropDown">
<option id="0" selected>I want to..</option>
<option id="1">Reset my password</option>
</select>
</div>
</div>
<div id="partialPlaceHolder" style="display:none;"> </div>
<script type="text/javascript">
$(document).ready(function () {
$('#myDropDown').change(function () {
/* Get the selected value of dropdownlist */
var selectedID = $(this).find('option:selected').attr('id');
/* Request the partial view with .get request. */
$.get('/Requests/FindPartial/' + selectedID, function (data) {
/* data is the pure html returned from action method, load it to your page */
$('#partialPlaceHolder').html(data);
/* little fade in effect */
$('#partialPlaceHolder').fadeIn('fast');
});
});
});
So when I select, "Reset my password" in the dropdown, I am successfully inserting my partial view into the div in my view. Below is my partial view.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="row">
<div class="col-lg-12">
<div class="well well-lg" style="text-align:left">
<div class="form-horizontal" id="resetpasswordform">
<h4>Reset Password</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.ServersList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ServerName, new SelectList(Model.ServersList))
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" id="submitButton" value="Reset" class="btn btn-default" />
</div>
</div>
</div>
</div>
</div>
</div>
}
<script>
$(function () {
$("#submitButton").click(function () {
debugger;
$.ajax({
type: "POST",
url: "Requests/Do_ResetPassword",
data: $("#resetpasswordform").serialize(),
success: function (data) {
debugger;
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
});
});
</script>
The problem is when the submit button is clicked, and I make the ajax post call, the $("#resetpasswordform").serialize() is always "" (empty string).
I tried making the view just with one element. I verified that the elements have name attribute for serialize to work. I also confirmed that I don't have a type=submit in my button. I changed the resetpasswordform into a form instead of div. I even rendered the partial view directly in Index.cshtml without dynamically populating. Nothing fixed the problem. All the time it returns empty string.
I verified all other similar questions in SO and not getting any hint on what i am doing wrong. Please help.
How about you set the id in the form tag:
#using (Html.BeginForm("action", "controller", FormMethod.Post, new { Id = "resetpasswordform" }))
and remove it from the div.

Categories