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
}
Related
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"
I'm using ajax to call a partial view with a table inside a div called "div-GVPrevision". I'm using datatables, but I'm getting an error after the ajax call, and it says:
"DataTables warning: table id=GVPrevision - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3"
This is the ajax code:
<script>
function GVPrevision() {
$('#GVPrevision').DataTable({
"aaSorting": [],
aLengthMenu: [
[4, -1],
[4, "Todo"]
],
responsive: false
});
}
$(document).ready(function () {
GVPrevision();
$('.btnagregar').click(function (event) {
event.preventDefault();
var data = {
"codmov": $("#codmovf").val(),
"fechainicio": $("#fechainiciof").val(),
"fechatermino": $("#fechaterminof").val(),
"rutentidad": $("#rutentidadf").val(),
"motivo": $("#motivof").val()
};
$.ajax({
url: "/Ficha/AgregarfooterPrevision",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$("#div-GVPrevision").load('#Url.Content("~/Ficha/GVPrevision")');
GVPrevision();
}
else
window.location.href = "#Url.Action("Prevision", "Ficha")";
},
error: function () {
console.log('Login Fail!!!');
}
});
});
});
</script>
as i believe the Database is initialized more then once since you are not showing the whole code i can only provide you this simple but not at all recommended soln is to destroy the data table and then call the GCPervision
AGAIN its not at all recommended soln but is a soln , Just use Distroy function
function GVPrevision() {
$('#GVPrevision').DataTable({
"aaSorting": [],
aLengthMenu: [
[4, -1],
[4, "Todo"]
],
responsive: false
});
}
$(document).ready(function () {
GVPrevision();
$('.btnagregar').click(function (event) {
event.preventDefault();
var data = {
"codmov": $("#codmovf").val(),
"fechainicio": $("#fechainiciof").val(),
"fechatermino": $("#fechaterminof").val(),
"rutentidad": $("#rutentidadf").val(),
"motivo": $("#motivof").val()
};
$.ajax({
url: "/Ficha/AgregarfooterPrevision",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$('#GVPrevision').DataTable().destroy();
$("#div-
GVPrevision").load('#Url.Content("~/Ficha/GVPrevision")');
GVPrevision();
}
else
window.location.href = "#Url.Action("Prevision", "Ficha")";
},
error: function () {
console.log('Login Fail!!!');
}
});
});
});
</script>
You have called the DataTable method 2 times here, one after the document.ready method & another in AJAX success method:
$(document).ready(function () {
GVPrevision(); // first call
$('.btnagregar').click(function (event) {
// data insertion here
$.ajax({
// other ajax options here
success: function (response) {
if (response.Success) {
$("#div-GVPrevision").load('#Url.Content("~/Ficha/GVPrevision")');
GVPrevision(); // second call - this will fail
}
else
window.location.href = "#Url.Action("Prevision", "Ficha")";
},
error: function () {
console.log('Login Fail!!!');
}
});
});
});
To solve this issue, you have 2 choices:
Remove one of the GVPrevision call either after document.ready or AJAX POST success part,
Use destroy method before creating another DataTable, together with bDestroy (sometimes the destroy method called fnDestroy, pick up which is the proper one for your DataTable version):
function GVPrevision() {
$('#GVPrevision').DataTable({
"aaSorting": [],
aLengthMenu: [
[4, -1],
[4, "Todo"]
],
responsive: false,
"bDestroy": true
}).destroy(); // or fnDestroy()
}
If you have DataTable version 1.10 or more, you can add destroy: true:
function GVPrevision() {
$('#GVPrevision').DataTable({
destroy: true // add this line
"aaSorting": [],
aLengthMenu: [
[4, -1],
[4, "Todo"]
],
responsive: false,
});
}
Reference:
Warning: Cannot reinitialise DataTable (DataTables Documentation)
Datatables warning(table id = 'example'): cannot reinitialise data table
I fixed the problem by replacing the code with the jquery $.post() method:
if (response.Success) {
$.post("/Ficha/GVPrevision", function (datos) {
$("#div-GVPrevision").html(datos);
GVPrevision();
})
}
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.
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
Can`t really understand where is a mistake..
I have a form with fileuploadfield. Request is sended good, action on my controller gets all params, works with them, and sends response to browser. But in html page, after submiting the form, always fires FAILURE event, and never SUCCESS.
Client Side Code
Ext.create('Ext.form.Panel', {
renderTo: 'Container',
bodyPadding: '10 10 0',
items: [
{
xtype: 'form',
width: 300,
border: false,
fileUpload: true,
items: [
{
xtype: 'combobox',
id: 'PayTypes',
width: 215,
store: PayTypesStore,
valueField: 'id',
displayField: 'Name',
editable: false,
name: 'id'
}
,
{
xtype: 'filefield',
id: 'form-file',
name: 'file',
buttonText: '',
buttonConfig: {
iconCls: 'upload-icon'
}
}
],
buttons: [
{
text: 'Send',
handler: function () {
var form = this.up('form').getForm();
if (form.isValid()) {
form.submit({
url: 'UploadFile',
waitMsg: 'Uploading your photo...',
success: function (fp, o) {
console.log("success");
msg('Success', 'Processed file on the server');
},
failure: function (form, action) {
console.log(action);
Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
}
});
}
}
}
]
}
]
});
Server Side Code:
public JsonResult UploadFile(HttpPostedFileWrapper file, int id)
{
var response = Json(new { success = true });
response.ContentType = "text/html";
return Json(response);
}
Response, recieved on the client side:
{"ContentEncoding":null,"ContentType":"text/html","Data":"success":true},"JsonRequestBehavior":1,"MaxJsonLength":null,"RecursionLimit":null}
What i need to fix in my code to get SUCCESS event after sumniting form?
You called Json method twice. The only thing you need is
public JsonResult UploadFile(HttpPostedFileWrapper file, int id)
{
return Json(new { success = true });
}