jquery mobile- override back device button event - jquery-mobile

I want the back button to toggle div for example.
How I can override the device back button event action?
I tried
document.addEventListener('backbutton', function() {
return false;
});
and the following code to evaluate after the page change
$(window).on("navigate", function (event, data) {
alert('abc');
event.stopImmediatePropagation();
return false;
});

Related

Using Javascript Bootbox with Ajax.BeginForm In ASP.NET

In view page:
#using (Ajax.BeginForm("UpdateAccount", "AccountInfo", new AjaxOptions {
HttpMethod = "POST",
AllowCache = false,
OnSuccess = "accountUpdateRequestSuccess",
OnFailure = "formSubmissionFailed",
OnBegin = "validateAccountInformation"
}))
validateAccountInformation function is stated below:
function validateAccountInformation() {
if (error.length > 0) {
showErrorNotification(errorListHtml);
return false;
}
else {
if ( Some Conditions ) {
bootbox.confirm({
title: "Confirm",
size: "medium",
message: "Some Message",
callback: function (result) {
if (result) {
Some Code
}
else {
Some Code
}
}
});
}
}
When Save button is clicked, at first validateAccountInformation function is called. If there's no error it will raise a Bootbox. If Bootbox OK button is clicked it'll submit the form with certain values or if Bootbox CANCEL button is clicked it'll submit the form with certain values different than before.
Now, the problem I'm facing is, when user clicks SAVE button it goes to validateAccountInformation function. And if there is no errors it calls Bootbox.Confirm. What I've expected that form submission will be held until some OK/CANCEL button is clicked in Bootbox. But it does not wait for Bootbox. Meaning Bootbox callback function is never called. It might have something to do with AJAX being asynchronous.
I've used javascript confirm method. And this method does hold form submission.
function validateAccountInformation() {
if (error.length > 0) {
showErrorNotification(errorListHtml);
return false;
}
else {
if ( Some Conditions ) {
if (confirm("check")) {
some code
}
}
}
}
Is there some way where I can use Bootbox Confirmation box with Ajax Begin Form as per scenario described above?
I've changed the flow and have been able to integrate Bootbox.
What I've done is, I've omitted the onBegin function. So my view page looks like this
#using (Ajax.BeginForm("UpdateAccount", "AccountInfo", new AjaxOptions {
HttpMethod = "POST",
AllowCache = false,
OnSuccess = "accountUpdateRequestSuccess",
OnFailure = "formSubmissionFailed",
}))
Now I've added a function which is fired by onclick event of this forms summit button. And integrated validateAccountInformation function and Bootbox within this function. Now the important part here is, this function always returns false. By returning false I've managed to hold on the form submission. Now the onClick event function looks like
$(document).on('click', '#btn-edit-account-save', function () {
var submit = validateAccountInformation();
some code
if (submit == true) {
if (some condition)
{
$('Form').submit();
}
else
{
bootbox.confirm(
{
title: "Confirm",
size: "medium",
message: "Some Message",
callback: function (result)
{
if (result)
{
$('Form').submit();
}
else
{
some code
}
}
});
}
}
return false;
});

Check SelectIndexChange/Blur Event In Jquery AutoComplete Combobox in MVC4

How can I get/check SelectIndexChange() or Blur() event In Jquery AutoComplete Combobox in MVC4 ?
You can bind on event Close ( it same blur ) and Select with call action through ajax request
View
$( ".selector" ).autocomplete({
select: function( event, ui ) { $.post(urlSelect); },
close: function( event, ui ) { $.post(urlClose); }
});
Controller
public ActionResult OnSelect()
{ // something }
public ActionResult OnClose()
{ // something }

MVC : How to clear session and close the current browser tab on click of logout?

How to clear session and close the current browser tab on click of log out ?
I am trying to clear session on tab close but not able to find correct way.
You can send an ajax request to to an action method which clears the session variables and in the call back, you can close the window.
<a id=logoutLink">Logout</a>
<script type="text/javascript">
$(function(){
$("#logoutLink").click(function(e){
e.preventDefault();
$.post("#Url.Action("Logout","User")",function(res){
if(res.status==="done")
{
//close the window now.
window.close();
}
});
});
});
</script>
Now in your UserController, Add the Logout action method
public class UserController : Controller
{
[HttpPost]
public ActionResult Logout()
{
Session.Abandon();
return Json(new { status="done"});
}
}

MVC - Load [HttpPost] view into Jquery/Ajax modal window

The way my code works currently is when a button is pressed variables are passed and Jquery unhides a modal window and makes an AJAX call to get the [HttpGet] portion of my Controller Action. This loads a form in the modal window. The modal has a save and cancel button, when the save button is pressed the form is submitted with ajaxSubmit. On successful save something is saved to the database, then a url is created and passed back to jquery and user is redirected with window.location.href.
What I'd like to have happen is when the save button is pressed the [HttpPost] part of controller action will make some logic choices, and if a certain condition is met within the action then return PartialView(model) is returned back to the modal window with an error message or pop up so that the user doesn't have to retype their information and understands why the save didn't go through and can edit quickly and try save again.
The Jquery:
var createNewClaimSetup = function () {
$(selectors.btnCreateNewClaim).live('click', function () {
var serialNumber = $(this).attr(attributes.serialNumber);
var spaRegistrationId = $(this).attr(attributes.spaRegistrationId);
var customerNumber = $(this).attr(attributes.customerNumber);
var customerStatementName = $(this).attr(attributes.customerStatementName);
$(selectors.serialNumberHidden).val(serialNumber);
$(selectors.spaRegistationIdHidden).val(spaRegistrationId);
$(selectors.customerNumberHidden).val(customerNumber);
$(selectors.customerStatementName).val(customerStatementName);
$(selectors.dialog).attr(attributes.title, 'Create New Claim');
$.ajax ({
url: inputs.warrantyClaimCreateUrl,
type: "GET",
data: {
serialNumber: serialNumber,
customerNumber: customerNumber
},
cache: false,
success: function (result) {
$(selectors.dialog).html(result.toString());
$(selectors.dialog).dialog ({
resizable: false,
height: 600,
width: 850,
modal: true,
buttons: {
'Save': function () {
// check to see if a value has been entered for problem description before submitting form
//
if(!$('#AddProblemModel_ProblemDesc').val().length==0 && (!$('#ClaimPrefix').val().length==0 || $('#chkManualClaimNum').is(':checked')))
$(selectors.createNewClaimForm).ajaxSubmit({
cache: false,
success: function (data) {
if (data.length == 0) {
location.reload();
$(selectors.dialog).dialog('close');
} else {
$(selectors.dialog).dialog('close');
window.location.href = data.redirectToUrl;
}
}
});
else{
return alert('You must select a prefix and enter a description for the problem before saving');
}
},
Cancel: function () {
$(this).dialog('close');
}
}
});
}
});
});
}
Controller Action GET (edited for brevity):
public virtual ActionResult WarrantyClaimCreateNew(string serialNumber, string customerNumber, string customerStatementName)
{
WarrantyClaimModel model = wcs.CreateNewClaimInfo(serialNumber, customerNumber, false);
ViewBag.InvalidPrefix = false;
ViewBag.DupeWaNum = false;
return View(model);
}
Controller Action POST (edited for brevity):
[HttpPost]
public virtual ActionResult WarrantyClaimCreateNew(WarrantyClaimCreateNewModel model)
{
if (ModelState.IsValid)
{
WaNumberDupeModel WAdupe = new WaNumberDupeModel(model.WarrantyClaimNumber);
// Rebuild WarrantyClaimModel object to pass back to view
WarrantyClaimModel model2 = wcs.CreateNewClaimInfo(model.SerialNumber, model.CustomerNumber, false);
// check if prefix is valid
if (WAdupe.DupeType == WaDupeType.InvalidPrefix)
{
ViewBag.InvalidPrefix = true;
return PartialView(model2);
//return Json(new { Url = Url.Action("WarrantyClaimCreateNew", model2) });
}
// check if wa number already exists
if (WAdupe.DupeExists)
{
ViewBag.DupeWaNum = true;
return PartialView(model2);
}
// create/save the new claim
if (wcs.CreateNewWarrantyClaim(model))
{
var redirectString = "WarrantyClaimDetail?warrantyClaimNumber=" + model.WarrantyClaimNumber;
if (Request.IsAjaxRequest())
{
return Json(new { redirectToUrl = redirectString }, JsonRequestBehavior.AllowGet);
}
return RedirectToAction(Actions.WarrantyClaimDetail(newClaimNumber));
}
return RedirectToAction(Actions.WarrantyClaimSaveFail());
}
else
{
return View(model);
}
}
Alerts In View If Conditions In Controller Action Met:
<%if (ViewBag.InvalidPrefix == true) { %>
alert("Please choose a valid prefix for your warranty claim number.");
<% } %>
<%if (ViewBag.DupeWaNum == true) { %>
alert("Warranty Claim Number already exists, please choose another manual WA number or try again.");
<% } %>
I haven't even been able to reload the view refreshed in the modal at all, let alone with changed to the bound model intact.
I know that the first part of the AJAX call (type: "GET") uses the URL to go into the controller action GET and gets back the return View(model) then converts it to HTML and sets the modal window HTML to it. I've been assuming that the ajaxSubmit goes back to the controller and gets the POST version of the action, and that the data part of success: function (data) should be the view return if condition is met and the built JSON URL to redirect to if it's not.
I've tried setting the modal html to data and making sure the controller invalid prefix condition is met, however the content in the modal window never seems to refresh. I'll also need to figure out how to logically tell in JQUERY if the controller returned a view or a URL through JSON but I don't think that will be hard to figure out.
I've read through a dozen or so mvc jquery ajax modal similar questions and they've helped but not
Thanks for any help shedding some light on how I might accomplish what a want here.
Sort of a partial answer to what I was looking for. I realize now my main stumbling block was to have my test alerts before building the modal window as "return alert(whatever)" which was obviously returning the alert and not running the rest of the code, dumb.
The solution I have working now is a pretty bad hack. I have it rebuild the modal and attach the POST view data to it. However this isn't looped so if you save and fail again I've set it to alert the user save failed again and to retry, then the modal closes and they can start again from scratch.
Tomorrow I'll see about turning this into a looping rather than nested structure.
New "working" JQuery code:
var createNewClaimSetup = function () {
$(selectors.btnCreateNewClaim).live('click', function () {
var serialNumber = $(this).attr(attributes.serialNumber);
var spaRegistrationId = $(this).attr(attributes.spaRegistrationId);
var customerNumber = $(this).attr(attributes.customerNumber);
var customerStatementName = $(this).attr(attributes.customerStatementName);
$(selectors.serialNumberHidden).val(serialNumber);
$(selectors.spaRegistationIdHidden).val(spaRegistrationId);
$(selectors.customerNumberHidden).val(customerNumber);
$(selectors.customerStatementName).val(customerStatementName);
$(selectors.dialog).attr(attributes.title, 'Create New Claim');
$.ajax ({
url: inputs.warrantyClaimCreateUrl,
type: "GET",
data: {
serialNumber: serialNumber,
customerNumber: customerNumber
},
cache: false,
success: function (result) {
$(selectors.dialog).html(result.toString());
$(selectors.dialog).dialog ({
resizable: false,
height: 600,
width: 850,
modal: true,
buttons: {
'Save': function () {
// check to see if a value has been entered for problem description before submitting form
//
if(!$('#AddProblemModel_ProblemDesc').val().length==0 && (!$('#ClaimPrefix').val().length==0 || $('#chkManualClaimNum').is(':checked')))
$(selectors.createNewClaimForm).ajaxSubmit({
cache: false,
success: function (data) {
if (data.length == 0) {
location.reload();
$(selectors.dialog).dialog('close');
} else if(data.redirectToUrl) {
$(selectors.dialog).dialog('close');
window.location.href = data.redirectToUrl;
} else {
$(selectors.dialog).html(data.toString());
$('#chkManualClaimNum').attr('checked','checked');
$('#manualClaimInfo').toggle();
$(selectors.dialog).dialog ({
resizable: false,
height: 600,
width: 850,
modal: true,
buttons: {
'Save': function () {
if(!$('#AddProblemModel_ProblemDesc').val().length==0 && (!$('#ClaimPrefix').val().length==0 || $('#chkManualClaimNum').is(':checked')))
$(selectors.createNewClaimForm).ajaxSubmit({
cache: false,
success: function (data) {
if (data.length == 0) {
location.reload();
$(selectors.dialog).dialog('close');
} else if(data.redirectToUrl) {
$(selectors.dialog).dialog('close');
window.location.href = data.redirectToUrl;
} else {
alert('Save failed again. Please start over.');
$(selectors.dialog).dialog('close');
}
}
});
},
Cancel: function () {
$(this).dialog('close');
}
}
});
}
}
});
else{
return alert('You must select a prefix and enter a description for the problem before saving');
}
},
Cancel: function () {
$(this).dialog('close');
}
}
});
}
});
});
}
This does at least show how to pass the POST view back to the modal window.

ASP.NET MVC two user control

I have two user controls on the page and one of the user control has this text aread.
which is used to add a note and but when they click add note button the page reloads.
I do not want the page to reload ,i was looking for an example which this is done without
postback.
Thanks
i tired doing this using JSON , but it throws the following error
The HTTP verb POST used to access path '/Documents/TestNote/Documents/AddNote' is not allowed.
<script type="text/javascript">
$(document).ready(function() {
$("#btnAddNote").click(function() {
alert("knock knock");
var gnote = getNotes();
//var notes = $("#txtNote").val();
if (gnote == null) {
alert("Note is null");
return;
}
$.post("Documents/AddNote", gnote, function(data) {
var msg = data.Msg;
$("#resultMsg").html(msg);
});
});
});
function getNotes() {
alert("I am in getNotes function");
var notes = $("#txtNote").val();
if (notes == "")
alert("notes is empty");
return (notes == "") ? null : { Note: notes };
}
</script>
</asp:Content>
Something like this would give you the ability to send data to an action do some logic and return a Json result then you can update your View accordingly.
Javascript Function
function AddNote(){
var d = new Date(); // IE hack to prevent caching
$.getJSON('/MyController/MyAction', { data: "hello world", Date: d.getTime() }, function(data) {
alert(data);
// call back update your view here
});
}
MyController Action
public virtual JsonResult MyAction(string data)
{
// do stuff with your data here, which right now my data equals hello world for this example
return Json("ReturnSomeObject");
}
What you want is AJAX update. There will always be a postback (unless you are satisfied with simple Javascript page update that does not save on the server), but it won't be the flashing screen effect any more.

Resources