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

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.

Related

asp.net javascript mvc - how can I get javascript from inner page to clear element from outer page?

I want javascript click event that's called from an "inner" mvc form to clear the element of the "outer"/"parent" form but clicking clear produces no results (see wireframe).
Javascript works on the outer form but not when called from scripts file reference in the inner form although I know that the script is wired up correctly b/c other behavior from the script is occurring.:
$("#clearField").on('click', function ()
{
document.getElementById("playerCardNumber").value = "";
});
Environment: asp.net mvc
Code for the outer/parent cshtml page:
#model adminLte.Models.playerCardData
<section class="content">
<div class="inputPlayerInfo">
#using (Ajax.BeginForm("WriteToGroup", "IT", new AjaxOptions //action, view
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "innerPlayerInfoForm", //css tag (see below)
OnComplete = "ReturnData",
OnBegin = "ClearResults",
LoadingElementId = "divloading"
}))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="divTable playerGroupTbl">
<div class="divTableBody">
<div class="divTableRow">
#Html.LabelFor(model => model.playerCardNumber , htmlAttributes: new { #class = "divTableCell" })
<div class="divTableCell">
#Html.EditorFor(model => model.playerCardNumber, new { htmlAttributes = new { #id= "playerCardNumber", #type ="password", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.playerCardNumber , "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<br />
<input type="submit" name="Command" value="Lookup Player" class="btn btn-default btn-lg" />
<button type="button" class="btn btn-default btn-lg" id="clearField" >Clear Previous Swipe</button>
}
</div>
<br />
#*form is inserted here*#
<div id="divloading" style="display:none">
<img src="~/images/giphy.gif" /> </div>
<div id="innerPlayerInfoForm"></div>
</section>
#section scripts{
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script>
function ReturnData()
{
$('#innerPlayerInfoForm').show();
}
function ClearResults()
{
$('#innerPlayerInfoForm').empty();
}
$('#playerEvent').selectpicker({
size: 4
});
$("#clearField").on('click', function () {
document.getElementById("playerCardNumber").value = "";
});
</script>
}
Code for the partial view:
#model adminLte.Models.eventModelParent
<div class="inputPlayerInfo">
#using (Ajax.BeginForm("sproc_PlayerGroupInsert", "IT", new AjaxOptions //action, view
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "innerPlayerInfoForm", //css tag (see below)
OnComplete = "ReturnData",
OnBegin = "ClearResults"
}))
{
#Html.AntiForgeryToken()
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
<div class="divTable playerGroupTbl">
<div class="divTableBody">
<div class="divTableRow">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="divTableCell">
Event:
</div>
<div class="divTableCell">
#foreach (var _event in Model.vips)
{
#Html.RadioButtonFor(m => m.events.SelectedEvent, _event.eventId,
_event.eventchecked == 1 ? new { #checked = "checked" } : null
) #:&nbsp #_event.eventName
<br />
}
#Html.ValidationMessageFor(model => model.events.SelectedEvent , "", new { #class = "text-danger" })
</div>
</div>
<div class="divTableRow" >
<div class="divTableCell"> Player ID: </div>
#foreach (var item in Model.playerData)
{
<div class="divTableCell">
<input style="border:none;background:transparent;" id="PlayerID" name="PlayerID" value=#item.PlayerID readonly>
</div>
}
</div>
<div class="divTableRow someDivXYZ">
<div class="divTableCell"> Player First Name: </div>
#foreach (var item in Model.playerData)
{
<div class="divTableCell">
<input style="border:none;background:transparent;" id="playerFirstName" name="playerFirstName" value=#item.playerFirstName readonly>
</div>
}
</div>
<div class="divTableRow someDivXYZ">
<div class="divTableCell"> Player Last Name: </div>
#foreach (var item in Model.playerData)
{
<div class="divTableCell">
<input style="border:none;background:transparent;" id="playerLastName" name="playerLastName" value=#item.playerLastName readonly>
</div>
}
</div>
</div>
</div>
<br />
<input type="submit" id="updatePlayerGroup" value="Write This Player to Group" class="btn btn-default btn-lg" />
<button onclick="ClearResults()" class="btn btn-default btn-lg" id="clearField">Clear Selected Data</button>
}
</div>
<div id="PlayerGroupInsertStatus"></div>
#Scripts.Render("~/scripts/renderJS.js")
External js file:
$('#playerEvent').selectpicker({
size: 4
});
$('#formEvent_playerEvent').selectpicker({
size: 4
});
function ReturnData() {
$('#PlayerGroupInsertStatus').show();
}
function beforeSend() {
var PlayerID = document.getElementById("PlayerID").value;
}
$("#clearField").on('click', function ()
{
document.getElementById("playerCardNumber") = "";
});
Any help is greatly appreciated - thanks in advance!

Limit the number of times a button can be pressed - C# ASP.NET MVC5 JavaScript

I have a page that allows you to create Income Types, but if you click the Create button, in succession then it creates multiple entries, Is there a way to have it limit this to you press it once and that is it?
I have looked at the code it uses an ajax method to get the information then post the form to the database. Some of my code below:
Index
#section scripts {
<script language="javascript" type="text/javascript">
#* DOM ready? *#
$(function () {
#* Pagination Async Partial Handling *#
$(document).on("click", "#indexPager a", function () {
if ($(this).parent().hasClass('disabled') || $(this).parent().hasClass('active'))
return false;
$.ajax({
url: $(this).attr("href"),
type: 'GET',
cache: false,
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
$(document).on("change", "#pageSizeSelector", function () {
var selectedValue = $(this).val();
$.ajax({
url: selectedValue,
type: 'GET',
cache: false,
success: function(result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
});
#* Sorting Async Partial Handling *#
$(document).on("click", "#tableHeader a", function () {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
cache: false,
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
#* Apply ACTION colours for hover *#
addTableStylingScripts();
});
</script>
}
#section additionalStyles {
#Styles.Render("~/plugins/datatables/media/css/cssDatatables")
}
#section modal {
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-12">
<div class="panel panel-visible" id="tableContainer">
#Html.Partial("_IncomeTypeManagementList", Model)
</div>
</div>
</article>
IncomeTypeManagementList
#* Header *#
<div class="panel-heading createContentTitle">
<div class="panel-title createLink">
<a href="#Url.Action("Create", "IncomeTypeManagement", new
{
page = Model.PagingInfo.Page,
take = Model.PagingInfo.Take,
sortBy = Model.PagingInfo.SortPropertyName,
sortAsc = Model.PagingInfo.SortAscending
})" data-container="body" data-toggle="tooltip" title="Add Income Type" id="createIncomeTypeLink">
<span class="fa fa-file"></span> Add Income Type
</a>
</div>
</div>
#* Body *#
<div class="panel-body pn">
<table class="table table-striped table-hover dataTable incomeTypesTable admin-form theme-primary" cellspacing="0" width="100%" role="grid">
<thead id="tableHeader">
<tr>
<th class="hidden-xs sorting #Html.SortTitleItem("IncomeTypeGroupId", Model.PagingInfo.SortPropertyName, Model.PagingInfo.SortAscending)">
<a href="#Url.Action("Index", "IncomeTypeManagement", new
{
page = 1,
take = Model.PagingInfo.Take,
sortBy = "IncomeTypeGroupId",
sortAsc = Model.PagingInfo.SortPropertyName != "IncomeTypeGroupId" || !Model.PagingInfo.SortAscending
})" data-container="body" data-toggle="tooltip" title="Sort by group">Group</a>
</th>
<th class="sorting #Html.SortTitleItem("Name", Model.PagingInfo.SortPropertyName, Model.PagingInfo.SortAscending)">
<a href="#Url.Action("Index", "IncomeTypeManagement", new
{
page = 1,
take = Model.PagingInfo.Take,
sortBy = "Name",
sortAsc = Model.PagingInfo.SortPropertyName != "Name" || !Model.PagingInfo.SortAscending
})" data-container="body" data-toggle="tooltip" title="Sort by name">Name</a>
</th>
<th class="hidden-xs sorting hidden-xs #Html.SortTitleItem("CreatedDate", Model.PagingInfo.SortPropertyName, Model.PagingInfo.SortAscending)">
<a href="#Url.Action("Index", "IncomeTypeManagement", new
{
page = 1,
take = Model.PagingInfo.Take,
sortBy = "CreatedDate",
sortAsc = Model.PagingInfo.SortPropertyName != "CreatedDate" || !Model.PagingInfo.SortAscending
})" data-container="body" data-toggle="tooltip" title="Sort by date">Created</a>
</th>
<th class="bg-white">
<div class="text-center">Action</div>
</th>
</tr>
</thead>
<tbody>
#foreach (var it in Model.IncomeTypes)
{
var actionId = "action_" + tableRowIndex;
var editIncomeTypeId = "editIncomeType_" + tableRowIndex;
<tr data-id="#it.ID"
data-isdeleted="#it.IsDeleted"
data-rowversion="#it.RowVersion"
data-createddate="#it.CreatedDate"
data-name="#it.Name"
data-incometypegroupid="#it.IncomeTypeGroupId"
data-incometypegroupname="#it.IncomeGroupName">
<td class="hidden-xs">
#it.IncomeGroupName
</td>
<td>
#it.Name.Truncate(50)
</td>
<td class="hidden-xs">
#it.CreatedDate.ToShortDateString()
</td>
<td class="updateTableRow text-center">
<div class="dropdownContainer btn-group text-right">
<button type="button" class="btn btn-primary br2 btn-xs fs12 dropdown-toggle" data-toggle="dropdown" aria-expanded="false" id="#actionId">
Action
<span class="caret ml5"></span>
</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li>
<a href="#Url.Action("Update", "IncomeTypeManagement", new
{
id = it.ID,
page = Model.PagingInfo.Page,
take = Model.PagingInfo.Take,
sortBy = Model.PagingInfo.SortPropertyName,
sortAsc = Model.PagingInfo.SortAscending
})" data-container="body" data-toggle="tooltip" id="#editIncomeTypeId" title="Edit" data-rowhover="editTableRow">
Edit
</a>
</li>
</ul>
</div>
</td>
</tr>
tableRowIndex++;
}
</tbody>
</table>
#Html.Partial("_Pagination", Model.PagingInfo)
</div>
Create
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript" type="text/javascript">
$(document).ready(function () {
#* Cancel *#
$(document).on("click", "#CancelForm", function (e) {
var uri = '#Html.Raw(Url.Action("Index", "IncomeTypeManagement", new
{
page = Model.PagingInfo.Page,
take = Model.PagingInfo.Take,
sortBy = Model.PagingInfo.SortPropertyName,
sortAsc = Model.PagingInfo.SortAscending
}))';
window.location = uri;
e.preventDefault();
});
});
</script>
}
#section additionalStyles {
}
#section modal {
}
<article class="row">
<h1 class="pageTitle incomeTypeHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-1"></div>
<div id="incomeTypeResults" 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 Income Type
</span>
</div>
#using (Html.BeginForm("Create",
"IncomeTypeManagement", FormMethod.Post,
new { id = "createIncomeType", role = "form", #class = "theme-primary form-horizontal" }))
{
#Html.AntiForgeryToken()
#* Pagination / Sorting *#
#Html.HiddenFor(m => m.PagingInfo.Page)
#Html.HiddenFor(m => m.PagingInfo.Take)
#Html.HiddenFor(m => m.PagingInfo.SortPropertyName)
#Html.HiddenFor(m => m.PagingInfo.SortAscending)
<fieldset>
<legend style="display: none">Create Income Type Form</legend>
#Html.HiddenFor(m => m.IsDeleted)
<div class="panel-body p25 fill bt0">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.IncomeTypeGroupId, new { #class = "control-label col-lg-2" })
<div class="col-lg-8">
#{
// get drop down values for DropDownFor()
var selectableItems = incomeTypeGroups.Select((v, idx) => new SelectListItem
{
Text = v.Value,
Value = v.Key,
Selected = idx == 0
});
}
#Html.DropDownListFor(m => m.IncomeTypeGroupId, selectableItems, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.IncomeTypeGroupId, string.Empty, new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Name, new { #class = "control-label col-lg-2" })
<div class="col-lg-8">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control", id = "Name", placeholder = "Name..." })
#Html.ValidationMessageFor(m => m.Name, 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 type="submit" class="btn btn-primary" id="SubmitForm" value="Create" />
</div>
</div>
</fieldset>
}
</div>
</div>
</article>
Update
section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript" type="text/javascript">
$(document).ready(function () {
#* Cancel *#
$(document).on("click", "#CancelForm", function (e) {
var uri = '#Html.Raw(Url.Action("Index", "IncomeTypeManagement", new
{
page = Model.PagingInfo.Page,
take = Model.PagingInfo.Take,
sortBy = Model.PagingInfo.SortPropertyName,
sortAsc = Model.PagingInfo.SortAscending
}))';
window.location = uri;
e.preventDefault();
});
});
</script>
}
#section additionalStyles {
}
#section modal {
}
<article class="row">
<h1 class="pageTitle incomeTypeHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-1"></div>
<div id="incomeTypeResults" class="col-md-10 formContainer">
<div class="panel">
<div class="panel-heading">
<span class="panel-title">
<i class="glyphicon glyphicon-pencil"></i> Details Of '#Model.Name'
</span>
</div>
#using (Html.BeginForm("Update",
"IncomeTypeManagement", FormMethod.Post,
new { id = "updateIncomeType", role = "form", #class = "theme-primary form-horizontal" }))
{
#Html.AntiForgeryToken()
#* Pagination / Sorting *#
#Html.HiddenFor(m => m.PagingInfo.Page)
#Html.HiddenFor(m => m.PagingInfo.Take)
#Html.HiddenFor(m => m.PagingInfo.SortPropertyName)
#Html.HiddenFor(m => m.PagingInfo.SortAscending)
<fieldset>
<legend style="display: none">Edit Income Type Form</legend>
#Html.HiddenFor(m => m.ID)
#Html.HiddenFor(m => m.RowVersion)
#Html.HiddenFor(m => m.IsDeleted)
<div class="panel-body p25 fill bt0">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.IncomeTypeGroupId, new { #class = "control-label col-lg-2" })
<div class="col-lg-8">
#{
// get drop down values for DropDownFor()
var selectableItems = incomeTypeGroups.Select((v, idx) => new SelectListItem
{
Text = v.Value,
Value = v.Key,
Selected = Model.IncomeTypeGroupId.ToString() == v.Key
});
}
#Html.DropDownListFor(m => m.IncomeTypeGroupId, selectableItems, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.IncomeTypeGroupId, string.Empty, new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Name, new { #class = "control-label col-lg-2" })
<div class="col-lg-8">
#Html.TextBoxFor(m => m.Name, new { #class = "form-control", id = "Name", placeholder = "Name..." })
#Html.ValidationMessageFor(m => m.Name, string.Empty, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="text-center">
<input type="button" class="btn btn-primary" onclick="this.disabled = true" id="CancelForm" value="Cancel" />
<input type="submit" class="btn btn-primary" id="SubmitForm" value="Update" />
</div>
</div>
</fieldset>
}
</div>
</div>
</article>
So I have tried adding <input type="submit" class="btn btn-primary" id="SubmitForm" value="Update" onclick="this.disabled = true" />
On the Create page When you click on Add Income Tye you are directed to the Create page, but when I have tied testing it the button is disabled, but then it does not submit anything and just remains on the Create page
To answer your question you kind of have to tackle the problem from 2 angles:
once click happens on your button you can either disable it or show an overlay so that no other elements on the page can be interacted with
you also have to think of what happens if some malicious user replays that request multiple times (by bypassing or altering the UI - which is dead easy to do) - on the server side you can use a processing queue of requests and every time you want to add a new request for processing, you can check to see if a duplicate exists
Unfortunately there isn't an easy answer for this. The 2nd part of the answer you have to think about it and assess if you're exposed to this issue. If your application is public and anyone can access it, don't assume that users will do everything on your system just via the UI.
Hope this helps.
This is what I come up with:
<script language="javascript" type="text/javascript">
$('.form-disable').on('submit', function () {
var self = $(this),
button = self.find('input[type="submit"], button'),
submitValue = button.data('submit-value');
button.attr('disabled', 'disabled').val((submitValue) ? submitValue : 'Please Wait...');
});
</script>
I added a class to the form so that when you click on a button that handles the submit, it disables the button and then waits with a message. But it only allows the button to be clicked once.

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.

Ajax script not working on Form Submit?

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())

How do I get Bootstrap file input data to controller in MVC 5

I'm using the Bootstrap File Input plugin to upload an image in my ASP.Net MVC 5 application form. I'm not sure what I need to see on the controller or what I need to do in javascript to get this to work. Currently there is an error that is being thrown when I submit my data in the form that says
"The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."
Here is my StudentController.
[HttpPost]
public ActionResult Edit(EditStudentViewModel studentViewModel)
{
if (ModelState.IsValid)
{
...other code left out
Here is my javascript
$("#input-20").fileinput({
'type': 'POST',
'cache': false,
'browseClass': 'btn btn-primary btn-block',
'showCaption': false,
'showRemove': false,
'showUpload': false,
'uploadAsync': false,
'maxFileCount': 1,
'allowedFileExtensions': ['jpg', 'png', 'gif'],
'allowedFileTypes': ['image']
'uploadUrl': '#Url.Action("Edit", "Student")'
});
*Are these the correct 'uploadUrl' parameters
Here is my form that submits the data to the controller. You can see I'm submitting what in the ViewModel as well as the image. The byte[] that represents the iamge is in the view model
#model YogaBandy.DomainClasses.ViewModels.Student.EditStudentViewModel
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.Partial("_MenuPartial")
<div class="row submenurow">
#Html.Partial("_StudentTeacherProfilePartial")
<div class="col-md-9 submenucol2">
#using (Html.BeginForm("Edit", "Student", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.StudentId)
#Html.HiddenFor(model => model.AspNetUserRefId)
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Student Picture</h3>
</div>
<div class="panel-body">
#Html.TextBoxFor(model => model.TestImage, new { #type = "file", #id = "input-20" })
</div>
</div>
<br/>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Student Profile</h3>
</div>
<div class="panel-body">
<div class="form-group">
#Html.LabelFor(model => model.CatchPhrase, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-sm-10">
#Html.EditorFor(model => model.CatchPhrase, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CatchPhrase, "", new { #class = "text-danger" })
</div>
</div>
...other form-group's left out below to save space
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}
</div>
Here is my ViewModel being submitted to the controller
public class EditStudentViewModel
{
public byte[] TestImage { get; set; }
...other values left out
}

Categories