How to call a non-static method from aspx - javascript

I've a Method in the code behind of my aspx page, I need to call Two methods from Javascript, the problem that I'm Having is that I was trying to do it with a Json request and a WebMethod, but this method has to be static and the page components and other methods cannot be accessed from this method.
I was trying something Like:
javascript Function
function Func(Value) {
var conf=confirm('Sure? '+valor)
if (conf==true)
{
BlockAction();
}
}
function BlockAction() {
$.ajax({
type: "POST",
url: 'frmVentaTelefonica.aspx/BlockAction',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
})};
Code-behind code:
[WebMethod]
public static void BlockAcction()
{
try
{
frmVentaTelefonica venta = new frmVentaTelefonica();
venta.ConsultarVentaTelefonica();
venta.ImprimirTiquetes();
}
catch (Exception e)
{
throw;
}
}
I want to call those two methods when the confirm is true.
Update:
In need to accesses to two methods like this:
public void ConsultarVentaTelefonica()
{
DatosImpresion = new List<Impresion>();
IServicioVentas servicioVentas;
servicioVentas = SATWebServiceLocator<IServicioVentas>.ObtenerServicio();
string Tiquetes = string.Empty;
foreach (GridDataItem dataItem in gridInfoVentaTelefonica.MasterTableView.Items)
{
if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked)
{
Tiquetes = Tiquetes + (dataItem["Tiquete"]).Text + ",";
}
}
Tiquetes = Tiquetes.TrimEnd(Tiquetes[Tiquetes.Length - 1]);
Tiquetes = " " + Tiquetes + " ";
DataSet dsResultado = servicioVentas.EntregaTelefonica(sessionR8A.Turno.IdTurno, Tiquetes);
if (dsResultado.Tables.Count > 0 && dsResultado.Tables[0].Rows.Count > 0)
Just run it when is true, those methods update in the database and print a ticket(first reading a grid checked items)

If you are trying to update the UI controls, or read their values, then what you are describing is the UpdatePanel control. A page webmethod cannot update any control and refresh the UI (unless through JavaScript). If you want to update the state of the page async, UpdatePanel is what you are looking for.

If you are trying javascript just because you dont want to refresh the page, then go for Update Panel . The answer for your question is 'No' you cant access non-static methods like how you want to do.
The reason it supports only static methods is that page instantiation is not done, if you want to use non static web methods then go for web service(.asmx).

Related

Value passed by ajax from Javascript to C#, Replied but not saved

I pass a value to my C# part with ajax and I get a response back. But I can't save the value or use it in my C# code. More information below:
Ajax Call: (gallery.aspx)
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&typeIds=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
Code Behind (CodeFile):(gallery.aspx.cs)
Update: Full C# code snippet
public partial class gallery : System.Web.UI.Page
{
public List<string> images = new List<string>();
public List<string> imagesList = new List<string>();
public List<string> filteredImagesList = new List<string>();
public List<string> testList = new List<string>();
protected string imagesName;
protected string filterType;
protected void Page_Load(object sender, EventArgs e)
{
if (Request["call"].ParseString() == "ajax")
{
Response.Write(Request["typeIds"].ParseString().TrimEnd(','), true, ResponseType.Json);
filterType = Request["typeIds"].ParseString().TrimEnd(',');
}
else
{
filterType = "Not Assigned!";
}
}
}
Output on the page: Not Assigned!
Meaning <h1><%=filterType%></h1> in aspx file returns the else statement from aspx.cs file
But I get the response back in my javascript while console.log("From AJAX: " + resp) shows the result.
BUT I can't use filtertype's value in my c# codefile.
I can't understand how come the Response.Write(Request["type"].ParseString().TrimEnd(','), true, ResponseType.Json); gives back the Request["type"] to js part but don't save it for my codefile. Should it be anything like Response.Read or Response.Save or something?
Does someone know what is going on in here?
You can store the ajax response in a hidden field and then access that hidden field value in server side code.
<asp:HiddenField ID="HiddenField1" runat="server" />
$.ajax({
url: Url, //assigned previously
data: 'call=ajax&method=GetList&type=' + typeIds.replace(",",""),
type: 'POST',
dataType: 'json',
success: function (resp) {
console.log("From AJAX: " + resp) // this works and shows the result
$('#<%=HiddenField1.CliendId%>').val(resp);
},
error: function (xhr, status) {
console.log("Sorry, there was a problem!");
}
});
You can then access in server side code like this:
HiddenField1.Value
OK. It will never be assigned in the way how you did it. Simply because when the page is loading and all controls are rendering no ajax calls are taking into account Page Life Cycles. Because of that on page load filterType is not assigned.
Although you have a couple of options
Use Ajax with update panel and PageRequestManager class
Change the value through JQuery or Vanilla JS by using <%=filterType.ClientID%>
If you need only front-end representation you can use either option. If you need it for further back-end I'm afraid option 1 only choice for you.

using ViewBag - asp.net mvc

In a asp.net mvc project i have this on top of my index.cshtml file
$.ajax({
url: '#Url.Action("getLoggedUser", "Home")',
dataType: "html",
"async": true,
type: "GET",
success: function (data) {
},
});
And the method it uses is this one, that is on HomeController
public async Task getLoggedUser()
{
try
{
BenchesService benchService = new BenchesService();
UserTest LoggedUser = new UserTest();
string name = Request.RequestContext.HttpContext.User.Identity.Name;
name = name.Substring(name.LastIndexOf('\\') + 1);
LoggedUser = await benchService.getCurrentUser(name);
role = LoggedUser.role;
ViewBag.LoggedUser = LoggedUser.role;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
This does a GET to the server with getCurrentUser(name); and that returns a json with user info, that i use to fill a UserTest object (i checked with break and the LoggedUser is filled correctly).
I want to save the user Role, to use in the html / javascript part
Then again on my index.cshtml i have this other script
$(document).ready(function () {
setTimeout(function () {
console.log("TIMER!");
userRole = '#ViewBag.LoggedUser';
alert(userRole);
}, 5000);
My problem is that the alert shows a empty message, like the ViewBag.LoggedUser has nothing. am i using ViewBag wrong?
Are you reloading your page? If not, your ViewBag has the same content like in the moment when page was rendering. Razor render text from ViewBag only on creation of html page, and if you are not reloading page, it will be always empty. You have to return your data in some object (ex. json) to ajax request and then you can use it.

onserverclick event not working using html builder in C#

I am using anchor tag and I want to fire event on click anchor tag.But unfortunately it is not working . Here is my code :
html.Append("<a id='dltTag' class='ca_quy_e' runat='server' onserverclick='Delete_Click'>");
html.Append("<i class='fa'>");
html.Append("</i>");
html.Append("</a>");
protected void Delete_Click(object sender, EventArgs e)
{
//My code
}
Every thing working perfect like table is forming , but only onserverclick not working.
You have to make use of javascript or jQuery i.e. clientside scripting for calling serverside method from client side
a. create method with wemethod attribute
[WebMethod]
public static string IsExists(string value)
{
//code to check uniqe value call to database to check this
return "True";
}
b. register client call with element
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
txtData.Attributes.Add("onblur", "focuslost()");
}
c. make use of jquery Ajax
function IsExists(pagePath, dataString, textboxid, errorlableid) {
$.ajax({
type:"POST",
url: pagePath,
data: dataString,
contentType:"application/json; charset=utf-8",
dataType:"json",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
$(errorlableid).show();
$(errorlableid).html("Error");
},
success:
function(result) {
var flg = true;
if (result != null) {
flg = result.d;
if (flg == "True") {
$(errorlableid).show();
}
else {
$(errorlableid).hide();
}
}
}
});
}
function focuslost() {
var pagePath = window.location.pathname + "/IsExists";
var dataString = "{ 'value':'" + $("#<%= txtData.ClientID%>").val() + "' }";
var textboxid = "#<%= txtData.ClientID%>";
var errorlableid = "#<%= lblError.ClientID%>";
IsExists(pagePath, dataString, textboxid, errorlableid);
}
if you are not getting than here is full article : Calling Server Side function from Client Side Script
if you are using scriptmanager than you can use this Execute server side code from JavaScript using Script Manager
you need to use _dopostBack for psotbacking to server or make use of ajax to call server side method
Read:
Usage of doPostBack in a Real Environment
Example
html.Append("<a id='dltTag' class='ca_quy_e' runat='server' onclick='DoPostBack()'>");
html.Append("<i class='fa'>");
html.Append("</i>");
html.Append("</a>");
function DoPostBack()
{
__doPostBack('DeleteButton','');
}

check duplicate data with javascript

i am writing web application in asp.net . i have a input form . i want when the client click on save Button before insert, check this data is in data base or not . i have written it with code behind . but i want do this with java script because when i i use code behind the page refresh . this is my .net code for check duplicate data:
SqlCommand commandrepeat1 = new SqlCommand("Select code from CmDet where code = " + txtcode.Text + " and company = " + DataBase.globalcompany.ToString() + " order by code desc");
commandrepeat1.Connection = objconnection;
objconnection.Close();
objconnection.Open();
SqlDataReader drmax1;
drmax1 = commandrepeat1.ExecuteReader();
drmax1.Read();
if (drmax1.HasRows)
{
MessageBox.Show("Duplicate data . try again!!! ");
txtcode.Focus();
objconnection.Close();
return;
}
objconnection.Close();
}
catch
{
objconnection.Close();
}
You should have your ASP.NET button implement both the OnClick event (to execute server-side code once it is determined that there is not duplicate data) and OnClientClick event (to execute your JavaScript that will call to check if there is duplicate data).
I suggest the following:
In JavaScript, add a jQuery click event to your button, like this:
$( "#myButton" ).click(function() {
});
Note: I have assumed the name of your button to be myButton, change it to match the ID of your button in markup.
Now you will need to call server-side to execute your logic to look for duplicate data. I recommend using ASP.NET AJAX Page Methods invoked via the jQuery .ajax() function, like this:
$.ajax({
type: "POST",
url: "YourPage.aspx/DoesDataExist",
data: "{'codeValue': $('#myTextBox').val()}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if(msg.d) {
// This is a duplicate, alert user with message
// Block the server-side click from happening with return false;
return false;
}
}
});
Finally, we need to build the server-side code that will handle the page method called by the jQuery above, like this:
[WebMethod]
public static bool DoesDataExist()
{
SqlCommand commandrepeat1 = new SqlCommand("Select code from CmDet where code = " + txtcode.Text + " and company = " + DataBase.globalcompany.ToString() + " order by code desc");
commandrepeat1.Connection = objconnection;
objconnection.Close();
objconnection.Open();
SqlDataReader drmax1;
drmax1 = commandrepeat1.ExecuteReader();
drmax1.Read();
if (drmax1.HasRows)
{
objconnection.Close();
return true;
}
objconnection.Close();
return false;
}

Retrieving data from controller on interval using AJAX in MVC3

For my company, we are building a web application for an invoicing system which utilises a notification bar, similar to that of Facebook, whereby the user can drop down a menu which displays the status of transactions on the system while a total number of outstanding transactions displays next to it. Please see the image for details.
http://img210.imageshack.us/img210/4379/alertdrop.png
We are retrieving the data for this using the following code for the table within the drop-down menu:
<table id="alertDropTable" style="margin-top:10px;">
#{
Dictionary<string, int> dic = ViewBag.statusCount;
if (dic != null)
{
for (int i = 0; i < dic.Count; i++)
{
if (dic.Values.ElementAt(i) > 0)
{
<tr>
<td width="100%" style="padding-bottom:4px; padding-top:4px; padding-left:10px; padding-right:10px; vertical-align:middle;">
You have <strong><a style="background-color:#878787; border-radius:5px; color:White; padding:3px;">#dic.Values.ElementAt(i)</a></strong> #dic.Keys.ElementAt(i) transaction(s).
</td>
</tr>
}
}
}
}
</table>
And the following for the span, which displays the total:
<div style="float: left;">
<img src="#Url.Content("~/Content/images/alert_notification.png")" name="alert" alt="alert"/>
#{
Dictionary<string, int> dicheader = ViewBag.statusCount;
int diccount = 0;
if (dicheader != null)
{
for (int i = 0; i < dicheader.Count; i++)
{
if (dicheader.Values.ElementAt(i) > 0)
{
diccount = diccount + #dicheader.Values.ElementAt(i);
}
}
}
}
</div>
<div id="alertTotalDiv" style="float:left;margin-top:6px; margin-left:5px;"><span id="alertTotal" style="vertical-align:middle; background-color:#878787; border-radius:5px; color:White; font-family:Georgia; font-size:20px; padding:3px; padding-left:5px; padding-right:5px;margin-top:0px;">#diccount</span></div>
This code is currently stored in the global "_layout.cshtml" file. Please excuse the roughness of the code, this is very much an early version. However, this is working fine in terms of retrieving the data on a page load. However, the system requires this information to be automatically updated every few seconds without refreshing the entire page. In essence, making a call to the controller to bring back the current data and update the <table> and <span> with the current values.
I have been asked to create an Ajax function which retrieves the data from the "AlertController" and updates the view accordingly. Please find the contents of this controller below:
public class AlertController : Controller
{
/// <summary>
/// Gets or sets the user service contract.
/// </summary>
/// <value>The user service contract.</value>
public IUserServiceContract UserServiceContract { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="BaseController"/> class.
/// </summary>
protected AlertController()
{
this.UserServiceContract = Gateway.Instance.Resolve<IUserServiceContract>();
}
/// <summary>
/// Get the AlertTypes
/// </summary>
/// <returns></returns>
public virtual void ViewAlerts()
{
Gateway.Instance.Logger.LogInfo(string.Format("Overview Controller View: Fetching list of alerts."));
try
{
if (this.UserServiceContract != null)
{
var allAnnouncements = this.UserServiceContract.GetAnnoucements();
var userAlertSettings = this.UserServiceContract.GetUserAlert();
ViewBag.statusCount = userAlertSettings;
ViewBag.announcements = allAnnouncements.ToList();
}
}
catch (Exception ex)
{
Gateway.Instance.Logger.LogInfo(ex);
throw new Exception(string.Format("Home Controller View Error: {0} occured while fetching alerts.", ex.Message), ex);
}
}
I am stumped, but have been given the following example of an Ajax function, which is used to perform a different task entirely, to aid me:
$.ajax({
url: '#Url.Action("ViewAlerts", "Alerts")',
data: { ownerIds: ownerIds },
traditional: true,
dataType: 'json',
success: function (result) {
for (i = 0; i < ownerIds.length; i++) {
$(".ownersTable tr[id='tablerow+" + ownerIds[i] + "']").remove();
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#confirmDiv").alertModal({
heading: '#Language.Fail',
body: '#Language.AlertRemoveOwnerFailed' + thrownError
});
}
});
Thus far, the only thing I've managed to get working was a set interval function, which makes an alert every 5 seconds!
Any guidance on this?
Okay, this is what you are going to need to do, first of all:
$.ajax({
url: '#Url.Action("ViewAlerts", "Alerts")',
data: { ownerIds: ownerIds },
traditional: true,
dataType: 'json',
success: function (result) {
for (i = 0; i < ownerIds.length; i++) {
$(".ownersTable tr[id='tablerow+" + ownerIds[i] + "']").remove();
}
},
error: function (xhr, ajaxOptions, thrownError) {
$("#confirmDiv").alertModal({
heading: '#Language.Fail',
body: '#Language.AlertRemoveOwnerFailed' + thrownError
});
}
});
Why is Url.Action in quotes? Just put #Url.Action ... I don't see a reason for the quotes and it may be breaking your call.
Second of all don't use ViewBag. It shouldn't be really used to hold 'data' (in my opinion). You should use a model. So this is what you can do:
Create the part of the page you want to update into a "Partial View" that is strongly typed to a model that contains the status and announcements and whatever else you need.
Use Jquery to 'Load' the Controller method that will get the data and return this 'Partial View', and load it into a Div on your screen example:
$('#div-to-load-into').load('/myactionurl/', function () { //Do something when done });
So your controller is then called, gets the data and returns the partial view with the model you created!
Good luck!
---Edit--- YOU should do above because it would be easier and faster (and if you do get to redesign you will quickly understand that, but here is an idea of how to do what you want)
This is what you need to know,
url is the action that the Ajax is going to call. You need to put url: '/controller/action'
data is the data you are sending to that action { parameter-name: parameter } it looks like in your case your sending no data because your only polling for a refresh, so you don't need to include this
dataType is the data you are expecting to be returned, it could be 'html' or 'json' , in your case your returning nothing because your using the 'ViewBag'
success will be called if the ajax call was successfully called with no errors with the result of that in 'result', in your case you have no result, because your using the view bag.
Now I can't promise this will work because I have never tried it:
function(result)
{
var updated_values = #Html.Raw(Json.Encode(ViewBag.AlertStatus))
}
Inside your success function on the ajax try this, this may or may not work. I honestly don't know if the ViewBag will have the updated values or not. At this point you only need to replace the table values with your new ones! you'll have to do all that in javascript, and I suggest looking at functions like 'appendTo', 'replaceWith', 'html' ect that are in Jquery to figure out how to do that.
$.ajax({
url: 'controller/action',
success: function (result) {
var alert_info = #Html.Raw(Json.Encode(ViewBag.AlertStatus))
},
error: function (xhr, ajaxOptions, thrownError) {
//error handling
}
});
(function checkStatus() {
$.ajax({
url: '#Url.Action("ViewAlerts", "Alerts")',
data: { ownerIds: ownerIds },
traditional: true,
dataType: 'json',
success: function (result)
{
for (i = 0; i < ownerIds.length; i++)
{
$(".ownersTable tr[id='tablerow+" + ownerIds[i] + "']").remove();
}
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(checkStatus, 5000);
}
});
})();
How to fire AJAX request Periodically?
In order to get data from an action to JavaScript, your action must return data. Right now your "action" is not really an action, as it returns void and sets ViewBag properties, which are not accessible from JavaScript. So your action needs to be something more like:
[HttpGet]
public ActionResult Alerts()
{
IEnumerable alerts;
// ...code which gets data into alerts
return JsonResult(alerts);
}
Obviously I don't know your domain, so I don't know how you would structure the data coming back, but the basics are there. The $.ajax call would point to the action route (in this case, probably '/Alert/Alerts'). The success function would have the data argument with the appropriate array of objects. From there you'd update your DOM with the data.

Categories

Resources