I have a jquery ui dialog that has a radio button list on it. I need to call a server side method when the user clicks ok and I need to pass the selected value. I tried doing it by calling an ajax method on and passing the selected value as a parameter. This worked great (the value was passed) but I could not access a cookie from the method (got error - Request is not available in this context), which makes sense being that this is an ajax request. Here is the code:
$("#dialogReject").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Reject": function () {
var value = $(this).find('input:checked').val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/myPage.aspx/RejectDocumentWM",
data: "{'rejectReason':'" + value + "'}",
dataType: "json",
success: function (data) {
alert('success');
},
error: function (result) { alert('error'); }
});
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog("close");
}
}
});
RejectDocument():
[WebMethod]
public static void RejectDocumentWM(string rejectReason)
{
MyNamespace.myPage page = new MyNamespace.myPage();
page.RejectDocument(rejectReason);
}
protected void RejectDocument(string rejectReason)
{
batch batch = (batch)Session["Batch"];
if (client.RejectDocument(batch.GetCurrentDoc().icn, rejectReason, Request.Cookies["username"].Value)) //here is where I get the error
{
NextDocument();
}
}
I tried doing it by putting the value into a hidden field and then calling a button click which calls a server side method. My problem here was that the hidden field's value was always blank even though it set properly in the client script. Here is the code for that:
$("#dialogReject").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Reject": function () {
var value = $(this).find('input:checked').val();
$('[id$="hdfRejectReason"]').val(value); //this sets properly
$('[id$="btnRejectDoc"]').click();
$(this).dialog('close');
},
Cancel: function () {
$(this).dialog("close");
}
}
protected void btnRejectDoc_Click(object sender, EventArgs e)
{
batch batch = (batch)Session["Batch"];
if (client.RejectDocument(batch.GetCurrentDoc().icn, hdfRejectReason.Value, Request.Cookies["username"].Value))
//hdfRejectReason.Value is blank
{
NextDocument();
}
}
Any ideas for me? I am at my wits end.
Thanks!
First of All, is this hf is in 'popup' or in 'main page' section?
Second, in stackoverflow, we discused and set other (better?) way to set hidden field value in jQuery:
<div class="hfFoo-wrap">
<asp:HiddenField runat="server" ID="hfFoo" />
</div>
function FooBarFunction() {
var hfFoo = $('.hfFoo-wrap input[type=hidden]');
hfFoo.val('Bar');
var isBar = hfFoo.val();
}
Maybe in btnRejectDoc_Click have other 'null' or 'empty' params?
Third: I prefere FrameDialog with 'aspx' page and 'callback delegate'.
create popup as 'aspx' page
open popup from 'main page' by jQuery as jQuery.FrameDialog
close dialog from 'aspx-popup' as 'close popup' (jQuery.FrameDialog.closeDialog();)
on 'main page' catch callback delegate (with params from popup) and set hidden field there
Related
I've got a Modal called #fileModal.
A 'Create File' button calls initCreateFile. This gets a form from an ajax call (c# PartialView) and loads the form into the #fileModal, and then shows the modal.
Second, eventFileValidation then creates a validation for the form.
Finally, submitCreateEventFile attaches a listener using .one to prevent multiple submissions.
There are some actions that seem to cause a multiple submissions.
First, closing the #fileModal, then reopening the modal with 'Create File', then submitting the form will cause a submissions equal to the amount times the modal was opened, with the most recent form data.
Second, if validation catches an error upon submission, then the user submits the form after fixing the validation error, it will submit multiple times.
I think what is happening is submitCreateEventFile is creating a listener each time initCreatefile is called. Validation may be also calling this, but I'm not sure. How can I prevent this from happening?
submitCreateEventFile: function (modal) {
$(modal).one("submit", "#create-event-file-form", function () {
event.preventDefault();
var fileModal = $('#fileModal');
closeModal(fileModal);
var waitModal = $('#waitModal');
initModal("", waitModal);
$.ajax({
type: 'POST',
url: urls.eventfilecreate,
data: new FormData(this),
contentType: false,
processData: false
}).done(function (file) {
closeModal(waitModal);
eventFileApp.addFile(file);
});
$(this).on('submit', function (evt) {
evt.preventDefault();
});
})
},
initCreateFile: function (element) {
var fileModal = $('#fileModal');
initModal("Create Event File", fileModal);
$.ajax({
type: 'GET',
url: urls.eventfilecreate,
data: { eventId: eventFileApp.getEventId(element) },
traditional: true
}).done(function (data) {
setModalContents(fileModal, data);
eventFileApp.eventFileValidation(fileModal);
eventFileApp.submitCreateEventFile(fileModal);
});
},
eventFileValidation: function (modal) {
var form = modal.find('form');
var isCreateForm = form.attr('id') == "create-event-file-form";
form.validate({
errorClass: "field-validation-error",
rules: {
Title: {
required: true
},
File: {
required: isCreateForm
}
},
messages: {
Title: {
required: "Title is required."
},
File: {
required: "File is required."
}
}
});
},
Adding $('#fileModal').off('submit') prior to calling the validation and submit methods prevented duplicate event listeners from being adding.
I am unable to call the web method from the click event of the dynamically added Button control.
Here is the C# Code
public partial class Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Button button = new Button();
button.Text = "Click Me.";
button.OnClientClick = "return Remove()";
pnlFiles.Controls.Add(button);
}
[WebMethod]
public void ClickEvent(int id)
{
}
}
Here is the javascript
<script type="text/javascript">
function Remove() {
$.ajax({
url:"Default.aspx/ClickEvent",
data: "{'id':5}",
type: "POST",
cache: false,
headers: { "cache-control": "no-cache" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (xhr, status, error) {
}
});
}
</script>
Here is the HTML
<asp:Panel runat="server" ID="pnlFiles" />
Any help in this regard is highly appreciated.
[WebMethod]
public void static ClickEvent(int i)
{
}
I think WebMethod should be static. Also Use JSON.stringify for data. This should solve the problem. If not, you can try and see if there is any error in network tab of chrome dev console.
Note: keep the param name of c# method same as the param you are passing in json body.
jQuery $.ajax error response text was "Authentication Failed". I commented out the following line in RouteConfig.cs and it worked.
jQuery $.ajax error response text is "Authentication Failed"
My full Calendar show data correctly using ajax . so i want to change the data on previous button click. But the button click function not working and how can i pass the data as parameter on previous and next button click
<script src="../assets/global/plugins/fullcalendar/lib/moment.min.js"></script>
<script src="../assets/global/plugins/fullcalendar/lib/jquery.min.js"></script>
<script src="../assets/global/plugins/fullcalendar/fullcalendar.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "attendance-full.aspx/GetEvents",
dataType: "json",
success: function (data) {
$('div[id*=calendar1]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: $.map(data.d, function (item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
return event;
}), eventRender: function (event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
$('div[id*=calendar1]').show();
//below code not working
$(".fc-prev-button span").click(function () {
alert("Hai");
})
});
My console is error free .
$(".fc-prev-button span").click(function () { runs before your calendar is created (because you wait to create the calendar until ajax has run, and ajax is asynchronous). Therefore there is no button for your code to bind the event to.
Simply move
$(".fc-prev-button span").click(function () {
alert("Hai");
});
to the end of your ajax "success" function.
N.B. I would also suggest that you re-consider how you're getting your events. Currently you fetch all events into the calendar, and the calendar cannot be displayed until the events are fetched. If your application is live for a long time, and builds up a lot of historical events, consider what will happen after a few years when there is a long list of events - it will take a long time to load them all, with no calendar on screen, and unless your situation is unusual, then probably no-one will look at anything from a long time ago, so it's a waste of time to load them.
FullCalendar is actually designed to work in a way that fetches only the events that are needed for the view and date range currently being displayed. So you fetch the minimum required events. If the user changes the view or date to something else, fullCalendar requests more events from the server, and sends it the date range required. This is usually much more efficient.
In your case you could re-write it something like this snippet below. Bear in mind you'd also have to change your GetEvents server method so that it filters the list of events by the dates supplied. I can't see that code so I can't advise exactly what you would need to do, but hopefully it will be fairly simple to add a couple of extra parameters and add a clause to your database query to compare the dates.
$(document).ready(function() {
$('div[id*=calendar1]').show();
$('div[id*=calendar1]').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
editable: true,
events: function(start, end, timezone, callback) {
$.ajax({
type: "POST",
contentType: "application/json",
data: '{ "start": "' + start.format("YYYY-MM-DD") + ', "end": ' + end.format("YYYY-MM-DD") + '}',
url: "attendance-full.aspx/GetEvents",
dataType: "json",
success: function(data) {
var events = $.map(data.d, function(item, i) {
var event = new Object();
event.id = item.EventID;
event.start = new Date(item.StartDate);
event.title = item.EventName;
return event;
});
callback(events);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
});
},
eventRender: function(event, eventElement) {
if (event.ImageType) {
if (eventElement.find('span.fc-event-time').length) {
eventElement.find('span.fc-event-time').before($(GetImage(event.ImageType)));
} else {
eventElement.find('span.fc-event-title').before($(GetImage(event.ImageType)));
}
}
},
});
$(".fc-prev-button span").click(function() {
alert("Hai");
});
});
See https://fullcalendar.io/docs/event_data/events_function/ for more details of the event feed function.
I have two buttons:
<center>
<p><button id="newuserbutton" >Create New User</button>
<p><button id="edituserbutton" >Edit User</button>
</center>
Clicking any of these button opens 'form1' over popup dialog using jQuery click function:
<script type="text/javascript">
// On DOM ready (this is equivalent to your $(document).ready(function () { ...} )
$(function() {
// Initialize modal (only once) on #div1
$('#div1').dialog({
modal: true,
autoOpen: false,
minHeight: 300
});
// Bind click on #newuserbutton button
$('#newuserbutton').click(function() {
$('#div1')
// Set buttons
.dialog("option", "buttons", [
{ text: "Create User", click: function() { $(this).dialog(""); } },
{ text: "Cancel", click: function() { $(this).dialog("close"); } }
])
// Set modal title
.dialog('option', 'title', 'Create new user')
// Set modal min width
.dialog({ minWidth: 550 })
// Open modal
.dialog('open');
});
// Bind click on #edituser button
$('#edituserbutton').click(function () {
$('#div1')
// Set buttons
.dialog("option", "buttons", [
{ text: "Save Changes", click: function() { $(this).dialog(""); } },
{ text: "Delete", click: function() { $(this).dialog("alert"); } },
{ text: "Cancel", click: function() { $(this).dialog("close"); } }
])
// Set modal title
.dialog('option', 'title', 'Edit User')
// Set modal min width
.dialog({ minWidth: 500 })
// Open modal
.dialog('open');
});
})
</script>
I need to use buttons (not above two) on dialog such as; "Create User", "Delete" etc. to manage my behind-code click events to manipulate a database. How i can do it? Thank you.
You could use an ajax call that can pass the data to the server and manipulate it there.
Steps
1.Create an asmx in your WebApplication (Add New Item > WebService) and name it MyService.asmx
2.Change the code-behind like this (it will be here - App_Code/MyService.asmx.cs)
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public string CreateUser(string userName, string password)
{
//here you can do all the manipulations with your database
return userName + " - " + password;
}
}
3.Now in the Create User Button's click event write this.
click: function () {
var DTO = {
userName: $("#username").val(),
password: $("#password").val()
};
$.ajax({
type: 'POST',
data: JSON.stringify(DTO),
url: "MyService.asmx/CreateUser",
contentType: 'application/json'
}).done(function (result) {
//check whether the result is wrapped in d
var msg = result.hasOwnProperty("d") ? result.d : result;
alert(msg);
}).fail(function (xhr) {
alert('Error: ' + xhr.statusText);
return false;
});
}
This is one way of doing it.
you can use the httphandler. you can create the method to update/Create User in handler and that method.you can call by using Jquery.
function CallHandler() {
$.ajax({
url: "Handler/MyHandler.ashx",
contentType: "application/json; charset=utf-8",
data: { 'Id': '10000', 'Type': 'Employee' },
success: OnComplete,
error: OnFail
});
return false;
}
Following code will be in handler.
public class MyHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
CreateUser();
}
public bool IsReusable {
get {
return false;
}
}
private Employee CreateUser()
{
}
}
When you call the Httphandler from jquery.It will hit to ProcessRequest. there you can perform code behind operation.
Try Adding runat="server" & onclick="function()" in button like :
<center>
<p><button id="newuserbutton" runat="server" onclick="function1()">Create New User</button>
<p><button id="edituserbutton" runat="server" onclick="function2()">Edit User</button>
</center>
Hope it can help.
If not, Another way can be to using ajax:
add onclick=ajaxcall()
2- in Javascript, add ajax call like:
`ajaxcall= function()
{
$.ajax({
type: "GET",
url: "youraspxpage.aspx/MethodName?data=AnyDataAsQueryString",
success: function(data){
$("#resultarea").text(data);
}
});
}`
OR
ajaxcall= function()
{
$.ajax({
type: "POST",
url: "youraspxpage.aspx/MethodName",
data:data,
success: function(data){
$("#resultarea").text(data);
}
});
}
3- Based on get or post use HttpGet or HttpPost attribute on public MethodName in code behind.
OR
alternatively try PageMethods, Check this link for more detail about pagemethods.
If I add a serverside function in masterlayout, the popup will display in all the pages. However, once I click the "no" button, it doesn't show anymore. For that, I have to use session, but we can't set the session value in jQuery.
The code behind I use in masterlayout is:
<script runat="server">
protected void btnCancel_Click(object sender, EventArgs e)
{
Session["sesvalue"] = 1;
}
</script>
but the method doesn't fire on button click
Your method must have static atribute.
[WebMethod]
public static string MethodName()
{
return "";
}
The way to call a server-side function from jQuery is via an ajax request. You don't need to put anything in Session, you can simply pass the value from the client side as an parameter to the function on the server side. Here's an example:
function ShowDialogAndCallServerSideFunction()
{
var $dialog = $('<div class="dialog"></div>')
.html('Dialog content goes here')
.dialog({
autoOpen: false,
width: 320,
title: 'Title goes here',
closeOnEscape: true,
buttons: [
{
text: "No",
click: function() { $(this).dialog("close"); }
},
{
text: "Yes",
click: function() {
$.ajax({
"type": "POST",
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"url": "WebServiceUrl.asmx/MethodName",
"data": "{'parameter': " + your_parameterHere + " }",
"success": function(result) {
//handle success here
},
"error": function(xhr, ajaxOptions, thrownError) {
//handle any errors here
}
});
$(this).dialog("close");
}
}
]
});
$dialog.dialog('open');
}
On the server side, you can have a Web Service - called WebServiceUrl on my example-:
[WebMethod]
public void MethodName(string parameter)
{
//the value received in 'parameter' is the value passed from the client-side via jQuery
}