In an aspx page, there is an asp:linkbutton like this:
<asp:LinkButton runat="server" ID="btExit" Text="Exit"
OnClientClick="javascript:return confirmExit();"
EnableViewState="false"
OnClick="ExitButtonClick"></asp:LinkButton>
And this is the javascript function:
<script type="text/javascript">
function confirmExit() {
bootbox.confirm("Are you sure?", function (confirmed) {
return confirmed;
});
}
</script>
The problem is that, as far as I know, bootbox.confirm works asynchronously, and ExitButtonClick function on code behind is executed without waiting for the user confirmation.
I found a solution that works, using a hidden button:
<asp:LinkButton runat="server" ID="btExit" Text="Exit"></asp:LinkButton>
<asp:Button runat="server" ID="btExitHidden" onclick="ExitButtonClick" style="display:none;" />
And this is the javascript part:
<script type="text/javascript">
$("#btExit").click(function (e) {
e.preventDefault();
bootbox.confirm("Are you sure?", function (confirmed) {
if (confirmed) {
$("#btExitHidden").click();
}
});
});
</script>
My question is if there is a more "beautiful" and "standard" way to work synchronously with a Bootbox.confirm, without using a hidden button.
You can make a custom sync bootbox function this way:
function ayncBootbox(message, cb = null) { // cb : function
return new Promise(resolve => {
bootbox.confirm({
message: message,
buttons: {
confirm: {
label: "Yes"
},
cancel: {
label: "No"
}
},
callback: cb ? result => cb(resolve, result) : result => resolve(result)
})
})
}
then you can call it this way by passing a custom callback if you need to do some extra stuff
var result = await ayncBootbox("message", (resolve, result) => resolve(result))
Or just
var result = await ayncBootbox("message")
PS: don't forget to make the caller function as async as well :) and you can extend this code more with reject if needed
My solution
#Html.ActionLink("Delete", "DeleteReport", new { id = item.Id }, new { #class = "btn btn-danger", onclick = String.Format("return ASE.ConfirmAction(this.href, 'Delete {0}?');", item.Name) })
var ASE = {
ConfirmAction: function (href, text) {
bootbox.confirm(text, function (result) {
if (result)
window.location = href;
});
return false;
}
}
Related
I am having this problem while working on an eshop I am building, I want to simply do a post request to a controller (that is not returning a view) while also submiting a form.. I do not know what is wrong with this code
<script>
$(document).ready(function () {
console.log("sad");
$("a[data-form-method='post']").click(function (event) {
event.preventDefault();
var element = $(this);
var action = element.attr("href");
element.closest("form").each(function () {
var form = $("#form1");
form.attr("action", action);
form.submit();
});
});
});
</script>
Here is the form
using (Html.BeginForm("SendEmailToAdmin", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.Hidden("receiver", $"{user.Email}");
Customer Support
}
Here is the controller
[HttpPost]
[Route("/Home/SendEmailToAdmin")]
//[NonAction]
public JsonResult SendEmailToAdmin()
{
........
(some code
if is true )
return Json(new { status = "Thank you very much admin for showing up. Don't forget to send us the email of your feedback on your way out" }, JsonRequestBehavior.AllowGet);
}
(or else)
return Json(new { status = "Something went wrong, please try again" }, JsonRequestBehavior.AllowGet);
I have tried also using a button with the id of submitDemo
$('body').on('click', function (e) {
e.preventDefault();
alert("Handler for .click() called.");
$.post("~/Home/SendEmailToAdmin");
});
and also
$("#form1").submit(function (event) {
event.preventDefault();
$.post('#Url.Action("SendEmailToAdmin", "Home",new { id = email })');
document.signupform.submit();
});
have also tried using a variable for the button and then with onclick method and so on...
const button = document.getElementById('submitDemo');
EDIT : I HAVE TRIED THIS
I fount it at last.. here it goes!
Jquery:
$(document).ready(function () {
$("#submitBtn").click(function (event) {
console.log("sad");
event.preventDefault();
$.ajax({
type: "POST",
url: "#Url.Action("SendEmailToAdmin", "Home")",
data: "#email",
success: function () {
console.log("Done")
$("#form1").submit();
}
});
});
});
html in view : I added the btn outside of the form
and this way the submit form happens and also the post request!
using (Html.BeginForm("AdminSupport", "Home", FormMethod.Post, new { id = "form1" }))
{
#Html.Hidden("receiver", $"{user.Email}");
#*<button id="submitbutton" #user.Email=>Customer Support</button>*#
}
<button id="submitBtn" #*data-form-method="post"*#>Customer Support</button>
I'm trying to write CRUD operations using ajax. Here some code:
These are my View classes:
//PhotoSummary
#model PhotoAlbum.WEB.Models.PhotoViewModel
<div class="well">
<h3>
<strong>#Model.Name</strong>
<span class="pull-right label label-primary">#Model.AverageRaiting.ToString("# stars")</span>
</h3>
<span class="lead">#Model.Description</span>
#Html.DialogFormLink("Update", Url.Action("UpdatePhoto", new {photoId = #Model.PhotoId}), "Update Photo", #Model.PhotoId.ToString(), Url.Action("Photo"))
</div>
//Main View
#model PhotoAlbum.WEB.Models.PhotoListViewModel
#{
ViewBag.Title = "My Photos";
}
#foreach (var p in #Model.Photos)
{
<div id=#p.PhotoId>
#Html.Action("Photo", new {photo = p})
</div>
}
The sript:
$('.dialogLink').on('click', function () {
var element = $(this);
var dialogTitle = element.attr('data-dialog-title');
var updateTargetId = '#' + element.attr('data-update-target-id');
var updateUrl = element.attr('data-update-url');
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = "<div id='" + dialogId + "'></div>";
$(dialogDiv).load(this.href, function () {
$(this).dialog({
modal: true,
resizable: false,
title: dialogTitle,
close: function () { $(this).empty(); },
buttons: {
"Save": function () {
// Manually submit the form
var form = $('form', this);
$(form).submit();
},
"Cancel": function () { $(this).dialog('close'); }
}
});
$.validator.unobtrusive.parse(this);
wireUpForm(this, updateTargetId, updateUrl);
});
return false;
});});
function wireUpForm(dialog, updateTargetId, updateUrl) {
$('form', dialog).submit(function () {
if (!$(this).valid())
return false;
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$(dialog).dialog('close');
$(updateTargetId).load(updateUrl);
} else {
$(dialog).html(result);
$.validator.unobtrusive.parse(dialog);
wireUpForm(dialog, updateTargetId, updateUrl);
}
}
});
return false;
});
}
And here my Tag builder:
public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string dialogContentUrl,
string dialogTitle, string updateTargetId, string updateUrl)
{
TagBuilder builder = new TagBuilder("a");
builder.SetInnerText(linkText);
builder.Attributes.Add("href", dialogContentUrl);
builder.Attributes.Add("data-dialog-title", dialogTitle);
builder.Attributes.Add("data-update-target-id", updateTargetId);
builder.Attributes.Add("data-update-url", updateUrl);
builder.AddCssClass("dialogLink");
return new MvcHtmlString(builder.ToString());
}
So, I have major problem if the dialog was called twice without the calling page being refreshed:
it just redirects me to the action page.
The question is how to update #Html.Action without reloading the page?
Could anyone help me?
Your #foreach loop in the main view is generating a partial view for each Photo which in turn is creating a link with class="dialogLink".
Your script handles the click event of these links and replaces it with a new link with class="dialogLink". But the new link does not have a .click() handler so clicking on the new (replacement) link does not activate your script.
Instead you need to use event delegation to handle events for dynamically generated content using the .on() method (refer also here for more information on event delegation). Note also that your current use of $('.dialogLink').on('click', function () { is the equivalent of $('.dialogLink').click(function () { and is not using event delegation. It attaches a handler to elements that exist in the DOM at the time the page is loaded, not to elements that might be added in the future.
Change your html to
<div id="photos">
#foreach (var p in #Model.Photos)
{
<div class="photo">#Html.Action("Photo", new { photo = p })</div>
}
</div>
and then modify the script to
$('#photos').on('click', '.dialogLink', function() {
....
});
Side note: There is no real need to add an id=#p.PhotoId to the containing div element and you could use <div class="photo"> as per above, and then reference it by using var updateTargetId = $(this).closest('.photo'); and delete the builder.Attributes.Add("data-update-target-id", updateTargetId); line of code from your DialogFormLink() method
I am using pagedList it is working but i need to have an ajax call to bring a new page i don't know how to do.
public ActionResult ApplicantsRecord(int page =1)
{
List<ApplicantsRecord> ar = new List<ApplicantsRecord>();
ApplicantsRecord a = new ApplicantsRecord();
List<ApplicantsRecordDetailViewModel> apvmlist = new List<ApplicantsRecordDetailViewModel>();
ApplicantsRecordDetailViewModel apvm = new ApplicantsRecordDetailViewModel();
//ar = db.ApplicantsRecords.ToList();
var groupedAR = db.ApplicantsRecords.GroupBy(x => x.SessionId)
.Select(y => new
{
SessionId = y.Key,
ApplicationsRecords = y.FirstOrDefault(),
}).ToList().OrderByDescending(x => x.ApplicationsRecords.LoginDate);
foreach (var i in groupedAR)
{
ar.Add(i.ApplicationsRecords);
}
if(Request.IsAjaxRequest())
{
return PartialView("_ApplicantsRecord", ar.ToPagedList(page, 10));
}
return View(ar.ToPagedList(page, 10));
}
and here is the view code
<div id="pagerecord">
#Html.Partial("_ApplicantsRecord");
</div>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var getpage = function () {
var $a = $(this);
var options = {
url: $a.attr("href"),
type: "get"
};
$.ajax(options).done(function (data) {
var target = $a.parents("div.pagedList").attr("next");
$(target).replaceWith(data);
});
return false;
};
$('main-conten').on('click', '.pagedList', getpage)
});
</script>
and here is the partial view
<table>
<thead>
<tr>
<th width="220" align="center">
<div class="pagedList" data-back-btn-text="next">
#Html.PagedListPager(Model, page => Url.Action("ApplicantsRecord", new { page }),
PagedListRenderOptions.MinimalWithItemCountText)
</div>
</th>
#*<th width="220" align="center">#Html.DisplayNameFor(model => model.UserName)</th>
<th width="220" align="center">#Html.DisplayNameFor(model => model.LoginDate)</th>
<th width="220" align="center">Details</th>*#
</tr>
</thead>
Did you try this already?
var getpage = function () {
var $a = $(this);
$.ajax({
url: $a.attr("href"),
type: "get",
success: function(data) {
var target = $a.parents("div.pagedList").attr("next");
$(target).replaceWith(data);
},
error: function() {
return false;
}
});
};
Next what you need tot do is:
Try to figure out if the data you are receiving is really the data you are expecting.
See if you do not enter the error function.
The first thing wrong is your selector is not a valid selector. $('main-conten') should probably be $('#main-conten') (assuming it is an element with an id of main-conten).
Secondly, you are using a delegated event handler, but listening for clicks on the .pagedList element and not the anchors within it:
$('main-conten').on('click', '.pagedList', getpage)
but inside the handler you are expecting the anchor to have been clicked as you are using:
var $a = $(this);
and
$a.attr("href")
Try something like this:
$(function () {
// Listen for clicks on anchors inside the paging panel
$('#main-conten').on('click', '.pagedList a', function () {
var $a = $(this);
var options = {
url: $a.attr("href"),
type: "get"
};
$.ajax(options).done(function (data) {
// Do something with the returned data
var target = $a.closest("div.pagedList").attr("next");
$(target).replaceWith(data);
});
return false;
});
});
Notes:
$(function () {YOUR CODE HERE}); is just a handy shortcut for $(document).ready(function(){});
Use closest() in preference to parents() where you only expect a single matching ancestor.
If all this still does not work, please post your HTML output (not source) as saved from the browser.
I am tying to validate the textboxes for achieving 'alphabets only' property in asp.net page with Jquery.
Here is the code
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
.............codes.............
<script type="text/javascript">
$('.alph').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else {
e.preventDefault();
alert('Alphabets only');
return false;
}
});
</script>
.............codes.............
<asp:TextBox ID="txt_name" CssClass="alph" BorderColor="Gray" Font-Size="Large" Height="25" Width="250" runat="server"></asp:TextBox>
This code didn't work and I am sure my computer is connected to the internet to reach code.jquery.com. Help me please.
try this script code after Document.ready block
$(document).ready(function(){
$('.alph').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else {
e.preventDefault();
alert('Alphabets only');
return false;
}
});
});
Before you can safely use jQuery you need to ensure that the page is in a state where it's ready to be manipulated. With jQuery, we accomplish this by putting our code in a function, and then passing that function to $(document).ready(). The function we pass can just be an anonymous function.
My mistake! Since I am new to Jquery I didn't know about 'doc.ready' I corrected the code as
$(document).ready(function () {
$('#<%=txt_name.ClientID %>').keypress(function (e) {
var regex = new RegExp("^[a-zA-Z\s]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (regex.test(str)) {
return true;
}
else {
e.preventDefault();
alert('Alphabets only');
return false;
}
});
});
Code works perfect!
I want to call a javascript and a function written in Model Class using a single button click. I used the following code:
<script language="javascript" type="text/javascript">
function RunEXE() {
var txtfile = document.getElementById("txtFileName");
//var txtProgram = document.getElementById("txtProgram");
//if ((!String.IsNullOrEmpty(txtfile)) && (!String.IsNullOrWhiteSpace(txtProgram))) {
if (txtfile.value != "") {
var oShell = new ActiveXObject("WScript.Shell");
//var prog = "c:\\Pgms\\sample0.exe";
var prog = "\\\\Test-PC\\Programms\\" + txtfile.value + ".exe";
oShell.Run('"' + prog + '"', 1);
} else {
alert('The file name must be entered in file name textbox');
}
}
</script>
<input type="submit" name="button" value="Run" onclick="RunEXE()" />
The below code is Model function:
public ActionResult Run(UserProgram userProgram)
{
SaveAndCompile(userProgram);
return null;
}
But its working with Run() alone and not running RunEXE()
[HttpPost]
public ActionResult RunAction(string option1)
{
//if needed, you can use the "option1" value to determine the UserProgram to pass
UserProgram userProgram = new UserProgram();
Run(userProgram);
//you can return a JSON reuslt that you can evaluate back at the client
return Json(new { #Success = true, #MyString = "a string" });
}
$.post('#Url.Action("RunAction", "MyController")',
{
option1: "some optional value"
},
function (data) {
alert("success!");
//here you have access to your JSON result via data, for example:
//data.Success = true
//data.MyString = "a string"
}
);
In your case, you can submit your form by JQuery submit function.
I assume your code will like below:
<form id="form" action="/Run">
// your some inputs
<input type="submit" name="button" value="Run" />
</form>
And the javascript for submitting will be:
$(function() {
$('#form').submit(function() {
// to do something before the form is submitted
RunEXE();
return true; // return false to cancel form action
});
});
Cheers.