Ajax multiple form not working - asp.net

<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div id="com-#Model.demot.DemotId">
#Html.Partial("_Comments", Model.demot.Comments)
</div>
#using (Html.BeginForm("AddComments", "Demot", new { DemotId = #Model.demot.DemotId}, FormMethod.Post, new { data_ajax = true, data_ajax_target = "com-" + #Model.demot.DemotId }))
{
#Html.AntiForgeryToken();
<div class="error-summary-centred">
#Html.ValidationSummary()
</div>
<div id="add">
<table id="albumedit-address-table">
<tr>
<td>#Html.TextBoxFor(o => o.comment, new { #class = "comment", placeholder = "Comment", value = "" })</td>
<td>#Html.ValidationMessageFor(o => o.comment)</td>
</tr>
</table>
</div>
}
</div>
</div>
<script>
$(function () {
$('form').on('submit', function (e) {
var $form = $(this);
var $target = $form.attr('data-ajax-target');
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
data: $(this).serialize(),
success: function (result) {
var $newContent = $(result);
$($('#' + $target)).replaceWith($newContent);
$newContent.effect("highlight");
$form.each(function(){
this.reset();
});
}
});
e.preventDefault();
});
});
</script>
I have many form in one page. My script work but only one time, subsequent requests sent to the server but no longer works adding results.
I would like to add comments ajax method worked all the time.
Please, any help.

You can try create a function that receive a parameter or ID when create a event.
For Example:
<script>
$(function() {
$('form').on('submit', function(e) {
var $form = $(this) functionAJAX(form)
})
});
functionAJAX() { /*His Code here*/ }
</script>

Related

I want to add a Select All checkbox using kendo grid in .NET MVC

Here's the code showing what I have done. Basically I have done coding for Select All but it's outside the Kendo grid. What I need is to place a Select All checkbox inside the column header from where I can do Select All function, which I am doing now by above Select All which is placed outside the Kendo grid.
This is what i need
#{
Layout = "~/Views/Admin/_Layout.cshtml";
ViewBag.PageTitle = "Profile status";
TempData.Keep("ProfileName");
ViewBag.PageHeaderName = "Clean Profile";
}
<div class="card card-body dprediction mx-3">
<div class="form-horizontal">
<div class="accordion" id="CreateETLToolProfile">
<div class="form-group row flex-v-center px-3 pt-2">
<div class="col-md-6 pt-3"> #ViewBag.ProfileName</div>
<div class="col-md-6" style="text-align:right">
<span class="pt-2">
Select All Tables #Html.CheckBox("IsSelectAllTables",true,new { #OnClick = "CheckUncheckCheckBox();" , id = "IDIsSelectAllTables" })
</span>
<button class="btn btn-primary" id="btnRefresh"><i class="fa fa-refresh"></i></button>
</div>
</div>
<div style="padding:5px 15px;">
#(Html.Kendo().Grid<DRS.Model.DTO.CleanProfileModel>()
.Name("CleanProfileGrid")
.Columns(columns =>
{
columns.Bound(c => c.DESTINATIONTABLEID).Hidden();
columns.Bound(c => c.DestinationTableName).Title("Dest Table name");
columns.Bound(c => c.DestinationSPName).Title("Dest SP name");
columns.Bound(c => c.IsToBeCleaned).ClientTemplate("<input type='checkbox' #= IsToBeCleaned ? checked='checked' :'' # class='chkbx' />").Title("Tables To Be Cleaned").Filterable(false).HeaderTemplate("<label for='check - all'>Tables To Be Cleaned </label><input type='checkbox' #= IsToBeCleaned ? checked='checked' :'' # class='chkbx1' />");
})
.Pageable()
.Sortable()
.Resizable(r => r.Columns(true))
.Filterable(filterable => filterable.Mode(GridFilterMode.Menu))
.Editable(editable =>
{
editable.DisplayDeleteConfirmation(false);
})
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(m => m.ID);
})
.PageSize(20)
)
.Events(events => events.DataBound("LoadCleanProfileGrid"))
)
</div>
<div class="card-body text-right pr-3">
#Html.ActionLink("Cancel", "ViewProfiles", "Admin", null, new { #class = "btn btn-secondary" })
<button id="btnSave" type="button" value="Save" class="btn btn-success">
<span class="glyphicon glyphicon-floppy-save"></span>
<span>Clean Profile</span>
</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function LoadCleanProfileGrid() {
// CheckUncheckCheckBox();
}
$(document).ready(function () {
debugger;
AssingCleanProfileGrid();
});
var ds = new kendo.data.DataSource();
function AssingCleanProfileGrid() {
var grid = $('#CleanProfileGrid').data('kendoGrid');
grid.setDataSource(ds);
grid.dataSource.read();
ds = new kendo.data.DataSource({
type: "aspnetmvc-ajax",
transport: {
read: {
url: '#Url.Action("GetJsonProfileDataForCleanPanel", "Admin")',
type: "POST",
dataType: "json",
}
},
schema: {
data: "Data",
total: function (response) {
return response.Total;
},
model: {
}
},
// serverPaging: true,
page: 1,
pageSize: 20,
skip: 0,
take: 15,
// serverSorting: true,
});
grid.setDataSource(ds);
grid.dataSource.read();
}
var IsClickedOnSelectAll = true;
function CheckUncheckCheckBox() {
debugger;
var IsSelctAll = true;
IsSelctAll = $("#IDIsSelectAllTables").prop("checked");
// alert(IsSelctAll);
var grid = $("#CleanProfileGrid").data("kendoGrid");
// var gridData = grid.dataSource.view();
var gridData = $('#CleanProfileGrid').data().kendoGrid.dataSource.data();
for (var i = 0; i < gridData.length; i++) {
var firstItem = $('#CleanProfileGrid').data().kendoGrid.dataSource.data()[i];
firstItem.set('IsToBeCleaned', IsSelctAll);
}
IsClickedOnSelectAll = true;
}
$(function () {
$('#CleanProfileGrid').on('click', '.chkbx', function () {
var checked = $(this).is(':checked');
var grid = $('#CleanProfileGrid').data().kendoGrid;
var dataItem = grid.dataItem($(this).closest('tr'));
dataItem.set('IsToBeCleaned', checked);
if (IsClickedOnSelectAll) {
$("#IDIsSelectAllTables").prop("checked", checked);
IsClickedOnSelectAll = false;
}
})
})
$("#btnRefresh").click(function () {
location.reload(true);
})
$("#btnSave").click(function () {
debugger;
var gridmodel = $("#CleanProfileGrid").data("kendoGrid").dataSource.data();
var CleanProfileGrid = JSON.stringify(gridmodel);
var ProfileName = '#ViewBag.ProfileName';
var CleanProfileId = '#ViewBag.CleanProfileId';
debugger;
$.ajax({
url: "#Url.Action("CleanProfileData", "Admin")",
type: "POST",
//dataType: "JSON",
data: { CleanProfileGrid: CleanProfileGrid, ProfileName: ProfileName, CleanProfileId:CleanProfileId},
success: function (result) {
}
});
window.location.href ='#Url.Action("ViewProfiles", "Admin")';
});
</script>
The Kendo Grid actually supports checkbox selection out of the box:
https://demos.telerik.com/aspnet-mvc/grid/checkbox-selection
If you opt for the built in selection, you can persist the selection between operations - paging/sorting/filtering/grouping.
As noted in another answer here, the grid has a built-in Select All function.
But in case you require a custom look or behavior, you can use Kendo column header templates for this. First, define your custom header representing the header with checkbox. This can be placed above the grid:
#helper MyHeaderTemplate() {
<span style='text-align:right'>My<br/>Header<br/>Checkbox<br/></span>
#(Html.CheckBox("MySelectAllBox", false,
new
{
style = "font-size:inherit; margin-top:5px",
#onchange = "handleSelectAllClick(this)"
})
)
}
Then reference the template from your grid:
#(Html.Kendo().Grid<DRS.Model.DTO.CleanProfileModel>()
.Name("myGrid")
.Columns(columns =>
{
columns.Bound(p => p.MyColumnProperty)
.HtmlAttributes(new { style="text-align:center" })
.HeaderHtmlAttributes(new { style = "text-align:center" })
.HeaderTemplate(#<text>#MyHeaderTemplate()</text>);
})
)
Then write some JavaScript to handle the handleSelectAllClick event as needed to select or deselect all grid rows.

DropdownList Doesn't Work on Mobile Devices

I have 2 dropdown list in my page. In web browser (PC side) It works fine. There is no problem. When i open the page with chrome toogle device toolbar and i resize as mobile view, it only gives this error
fastclick.js:1 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080
csHTML Code
<div class="tab-pane active tabcontent" id="reservationPage" role="tabpanel">
<div class="col-sm-12 col-md-12">
<div class="form-group row rowR">
<label class="form-control-label col-md-2"><strong>Yemekhane</strong> </label>
<div class="col-md-12">
#Html.DropDownListFor(x => x.RefectoryId, new SelectList(Model.Refectories, "Id", "Name"), ("Seçiniz"), new { Id = "RefectoryId", #class = "form-control select2" })
</div>
</div>
<div class="form-group row rowR">
<label class="form-control-label col-md-2"><strong>Öğün</strong> </label>
<div class="col-md-12">
#Html.DropDownListFor(x => x.FoodMealId, new SelectList(Model.FoodMeals, "Id", "Name"), ("Seçiniz"), new { Id = "FoodMealId", #class = "form-control select2" })
</div>
</div>
</div>
</div>
JS Code
<script>
var reservationCount = 0;
var totalAmount = 0;
$(document).ready(function () {
$("#reservationCount")[0].textContent = "(" + reservationCount + ")";
//İlk açıldığında rezervasyon sayfasının acık gelmesi için
var tablinks = document.getElementById("reservationPageHead");
tablinks.className = tablinks.className + " active";
document.getElementById('reservationPage').style.display = "block";
//var foodMealId = $("#FoodMealId").val();
//var refectoryId = $("#RefectoryId").val();
//GetCalendarMenuPartial(foodMealId, refectoryId);
$("#RefectoryId").select2({
allowClear: true,
placeholder: 'Yemekhane Seçiniz',
// dropdownParent: $(".bootbox-body"),
});
var refectorySelect = $('#RefectoryId');
refectorySelect.on("select2:select", function (e) {
var foodMealId = $("#FoodMealId").val();
var refectoryId = $("#RefectoryId").val();
$.ajax({
url: "#Url.Action("GetRefectoryWithFoodMeal", "Reservation", new { area = "Common" })",
data: { refectoryId: refectoryId },
type: "POST",
async: false,
success: function (returnData) {
if (returnData.data == undefined) {
PageToastr(returnData.type, returnData.message, returnData.title);
}
else {
//FoodMeal List
$("#FoodMealId option[value]").remove();
$("#FoodMealId").select2({
allowClear: true,
placeholder: 'Seçiniz',
data : returnData.data,
});
}
},
beforeSend: function () {
$(".loaderDiv").show();
$(".loader").show();
},
complete: function () {
$(".loaderDiv").hide();
$(".loader").hide();
},
error: function (xhr, status, err) {
if (xhr.status === 999) {
noAuthorize(this.url);
}
}
});
var foodMealId = $("#FoodMealId").val();
var refectoryId = $("#RefectoryId").val();
GetCalendarMenuPartial(foodMealId, refectoryId);
});
$("#FoodMealId").select2({
allowClear: true,
placeholder: 'Öğün Seçiniz',
//dropdownParent: $(".bootbox-body"),
});
var foodMealSelect = $('#FoodMealId');
foodMealSelect.on("select2:select", function (e) {
var foodMealId = $("#FoodMealId").val();
var refectoryId = $("#RefectoryId").val();
GetCalendarMenuPartial(foodMealId, refectoryId);
});
// Rezervasyonu tamamla için tooltip
$('#completeReservation').tooltip('update');
});
</script>
<script>
function GetCalendarMenuPartial(foodMealId, refectoryId) {
$.ajax({
url: '#Url.Action("NewReservationCalendarMenuPartial", "Reservation", new { area = "Common" })',
data: { foodMealId: foodMealId, refectoryId: refectoryId, addCardMenu: $("#AddCardMenuString").val() },
type: "POST",
success: function (partialPage) {
if (partialPage.title != undefined) {
PageToastr(partialPage.type, partialPage.message, partialPage.title);
if (partialPage.result == '#Enums.ResultStatus.SessionTimeExpired.ToString()') {
setTimeout(function () { window.location.href = '/Login/Login'; }, 5000)
}
}
else {
$("#calendarMenuPartial").html(partialPage);
}
},
beforeSend: function () {
$(".loaderDiv").show();
$(".loader").show();
},
complete: function () {
$(".loaderDiv").hide();
$(".loader").hide();
},
error: function (xhr, status, err) {
if (xhr.status === 999) {
noAuthorize(this.url);
}
}
});
}
</script>
After that I've added touch-action: none; but it doesn't work too. It works properly in PC Devices. But never works on mobile devices.

Two recaptcha controls, one of them is not working

I have two reCaptcha V2 controls within two forms in one page, one is visible another is invisible. All is fine except the invisible one's data-callback callback - submitSendForm() did not get called. Once I removed the visible one, the invisible one starts working.
So the process is like once user completed the first visible challenge then the second form(within same page) will show with the invisible one, that's when the call back failed to be called.
It hasn't to be one visible and another invisible. But I found this to be easy when you want to have multiple controls.
Here is the code:
using (Html.BeginForm("Verify", "CertificateValidation", FormMethod.Post, new { id = "verifyForm" }))
{
<div class="form-group">
<div class="g-recaptcha" data-sitekey='site-key' data-callback="enableBtn"
style="transform: scale(0.66); transform-origin: 0 0;">
</div>
<div class="col-sm-3">
<button type="submit" id="verify" disabled>Verify</button>
</div>
</div>
}
using (Html.BeginForm("Send", "CertificateValidation", FormMethod.Post, new { id = "sendForm" }))
{
<div id='recaptcha1' class="g-recaptcha"
data-sitekey='site-key'
data-callback="submitSendForm"
data-size="invisible"></div>
<button type="submit">Send</button>
}
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script type="text/javascript">
function submitSendForm() {
console.log('captcha completed.');
$('#sendForm').submit();
}
$('#sendForm').submit(function (event) {
console.log('form submitted.');
if (!grecaptcha.getResponse()) {
console.log('captcha not yet completed.');
event.preventDefault(); //prevent form submit
grecaptcha.execute();
} else {
console.log('form really submitted.');
}
});
var enableBtn = function (g_recaptcha_response) {
$('#verify').prop('disabled', false);
};
$(document).ready(function () {
$('#verify').click(function () {
$captcha = $('#recaptcha');
response = grecaptcha.getResponse();
if (response.length === 0) {
return false;
} else {
return true;
}
});
});
</script>
I got it figured out somehow:
var CaptchaCallback = function () {
grecaptcha.render('RecaptchaField1', { 'sitekey': 'site-key', 'callback': 'enableBtn' });
window.recaptchaField2Id = grecaptcha.render('RecaptchaField2', { 'sitekey': 'site-key', 'callback': 'submitSendForm', 'size': 'invisible' });
};
function submitSendForm() {
$('#sendForm').submit();
}
$('#sendForm').submit(function (event) {
if (!grecaptcha.getResponse(window.recaptchaField2Id)) {
event.preventDefault();
grecaptcha.execute(window.recaptchaField2Id);
}
});
using (Html.BeginForm("Verify", "CertificateValidation", FormMethod.Post, new { id = "verifyForm" }))
{
<div class="form-group">
<div style="transform: scale(0.66); transform-origin: 0 0;" id="RecaptchaField1"></div>
<div class="col-sm-3">
<button type="submit" id="verify" disabled>Verify</button>
</div>
</div>
}
using (Html.BeginForm("Send", "CertificateValidation", FormMethod.Post, new { id = "sendForm" }))
{
<div id="RecaptchaField2"></div>
<button type="submit">Send</button>
}
This one worked for me, clean and easy.
Javascript
var reCaptcha1;
var reCaptcha2;
function LoadCaptcha() {
reCaptcha1 = grecaptcha.render('Element_ID1', {
'sitekey': 'your_site_key'
});
reCaptcha2 = grecaptcha.render('Element_ID2', {
'sitekey': 'your_site_key'
});
};
function CheckCaptcha1() {
var response = grecaptcha.getResponse(reCaptcha1);
if (response.length == 0) {
return false; //visitor didn't do the check
};
};
function CheckCaptcha2() {
var response = grecaptcha.getResponse(reCaptcha2);
if (response.length == 0) {
return false; //visitor didn't do the check
};
};
HTML
<head>
<script src="https://www.google.com/recaptcha/api.js?onload=LoadCaptcha&render=explicit" async defer></script>
</head>
<body>
<div id="Element_ID1"></div>
<div id="Element_ID1"></div>
</body>

Ajax call is not working in View(ASP.NET MVC 5). How do I solve it?

My actions returns a Json to my view, however, my ajax call can't use this data, so, whole data is put on the browser.
That's my action is my controller:
[HttpGet]
public JsonResult InformarPatrocinador()
{
//return View("CadastrarFicha");
/*
Patrocinador patr = new Patrocinador
{
NomeDoPatrocinador = "João",
Id_Patrocinador = 10000
};*/
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
return Json(db.Tabela_Participante.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
That's my view(Where the Ajax Call is)
#model FlowerMorena_WebUI.Models.ViewModelFicha
#{
ViewBag.Title = "InformarPatrocinador";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Informar Patrocinador</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary();
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title text-center">Patrocinador</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="form-group col-xs-12 col-lg-offset-4">
<label> Código do Patrocinador </label>
#Html.TextBoxFor(x => x.Patrocinador.Id_Patrocinador, new { #class = "form-control", id = "IdDoMeuPatr" })
</div>
<div class="form-group col-xs-12 col-lg-offset-4">
<label> Nome do Patrocinador </label>
#Html.TextBoxFor(x => x.Patrocinador.NomeDoPatrocinador, new { #class = "form-control center-block", disabled = "disabled", #readonly = "readonly", id = "NomePatr" })
</div>
<div class="form-group col-xs-12 col-lg-offset-4">
<input class="btn btn-success" value="Avançar" id="buttonx" />
</div>
</div>
</div>
</div>
}
<ul id="aLista"></ul>
#section scripts{
<script type="text/javascript">
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: '/Ficha/InformarPatrocinador',
type: 'GET',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
$('aLista').append("<li>" + item.Nome + "<li>")
});
}
});
});
});
</script>
}
That's what I got(Ajax call did nothing))
are you calling your Action like localhost:0000/Ficha/InformarPatrocinador ?
and if you are doing this then this action will always return the result you have shown in picture.
you should make another post Action like
[HttpPost]
public JsonResult InformarPatrocinador()
{
}
and change your Ajax method to Post
$.ajax({
url: '/Ficha/InformarPatrocinador',
type: 'POST',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
$('aLista').append("<li>" + item.Nome + "<li>")
});
}
});
and it should work fine.

jCryption ASP.Net MVC

Our security team asked me to not submit plain text passwords in my log in page, we use HTTPS though. so I thought that I need to do client side encryption before submit, I searched for solution and decided to implement jCryption.
However the example presented there is PHP/python, after a few google found this. I did whatever was explained in the link but I don't know how to retrieve form data that user submitted in form.
I only see a key returns in my login post back action and the LoginModel that should contain username, password is null.
Login.cshtml
#model Portal.Model.Membership.LoginModel
#using jCryption
#{
Layout = null;
jCryption.HandleRequest(Request);
}
<html>
<head>
<script src="~/Assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="~/Assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script>
#jCryption.RenderScriptFor("form", src: #Url.Content("~/Assets/admin/scripts/jquery.jcryption.3.1.0.js"))
</head>
<body>
#using (Html.BeginForm(null, null, FormMethod.Post, new { #autocomplete = "off" }))
{
<div class="form-body">
<div class="form-group">
#Html.LabelFor(x => x.Username, new { #class = "placeholder" })
#Html.TextBoxFor(x => x.Username, new { #class = "form-input", autocomplete = "off" })
<span></span>
</div>
<div class="form-group">
#Html.LabelFor(x => x.Password, new { #class = "placeholder" })
#Html.PasswordFor(x => x.Password, new { #class = "form-input", autocomplete = "off" })
<span></span>
</div>
</div>
<div class="form-group">
<button id="btnLogin">Login</button>
</div>
}
</body>
<!-- END BODY -->
</html>
Update
I put break point on login post action and it popup twice, one with key and another with jCryption:
For MVC 5, you need to adjust a little bit.
at login.cshtml
#using jCryption
#{
jCryption.HandleRequest(Request);
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="/Scripts/jquery.jcryption.3.1.0.mod.js"></script>
<script type="text/javascript">
// tweak for compatibility with jquery.validate
(function($){
var _jCryption = $.jCryption;
var jCryptionMod = function(el,options){
var form = $(el), hasValidator = !!form.data('validator');
if (hasValidator){
var v = form.validate();
var prev_handler = v.settings.submitHandler;
v.settings.submitHandler = function (_form, event) {
if( prev_handler ) prev_handler.apply(this, arguments);
var form = $(_form);
if (!form.hasClass('jc-before-submit')) {
v.settings.submitHandler = prev_handler;
form.addClass('jc-before-submit');
setTimeout( function(){ form.trigger('_jc_submit', event); }, 100 );
}
};
_jCryption.call(this, form, $.extend(options, {
submitElement: form,
submitEvent: '_jc_submit',
beforeEncryption: function(){
form.removeAttr('disabled');// form element hack ( IE11 )
return true;
}
}));
} else {
return _jCryption.call(this,el,options);
}
}
$.extend(jCryptionMod, $.jCryption);
$.jCryption = jCryptionMod;
})(jQuery);
</script>
<script type="text/javascript">
$(document).ready(function(){
var form = $('form');
var url = form.attr('action') || '/Account/Login';
form.jCryption({
getKeysURL: url + '?getPublicKey=true',
handshakeURL: url + '?handshake=true'
});
});
</script>
}
AccountController, you should follow JakeJP's documentation (exact same code).
At IE F12 Developer Tools (Network-->go to detail view-->Request body), it showns &jCryptionKey= but not &UserName= and &Password=.
You lack the jCryptionHandler attribute in your action method. The attribute is responsible for handling the jCryption handshake and decryption.
[jCryptionHandler]
public ActionResult Login(LoginModel model)
{
return View();
}

Resources