I am trying to get access a drop-down that is in aspx page from static web method but it seems i can't get access and not what am i doing wrong. I want to set the dropdown index value to -1. thanks
this is what i am trying to do:
[System.Web.Services.WebMethod]
public static void Cancel()
{
myDDL.SelectedIndex = -1;
}
here is the javascript call
<script type="text/javascript" language="javascript">
function Func() {
//alert("hello!")
var result = confirm('WARNING');
if (result) {
//click ok button
PageMethods.Delete();
}
else {
//click cancel button
PageMethods.Cancel();
}
}
</script>
I am trying to get access a drop-down that is in aspx page from static web method
the web method in asp.net page are static, this mean are executed without page context(not completely true, you can access to Session), so what you need its retrieve result from web method, then make your update client side, something like(not tested, sorry):
jQuery.ajax({
url: 'callAJAX.aspx/Cancel',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var result = data.d.result;
$('#yourDropDownID')[0].selectedIndex = result;
}
});
It should be myDDL.selectedIndex = -1;
You cannot access a control inside webmethod..At the web service method level you cannot see anything about the page structure..
You can try this code for clearing dropdown..
Instead of calling pagemethod Cancel you can clear it inside javascript function itself..
var ddl = document.getElementById('myDDL');
ddl.options[ddl.selectedIndex] = 0;
Refer this link for extra reading..
Related
I'm working with an asp.net MVC project. A coworker was new to MVC and handled all of the populating of data and click actions by using ajax calls. I know this isn't how MVC should be set up, but it's what I'm stuck with. I'm just trying to work around that the best I can. Anyway, within the method the ajax goes to, I need to redirect the user to a new page. How do I do that?
I tried Response.Redirect, but I got an error saying it didn't exist. I tried to add a using class, but couldn't it to work.
I found System.Diagnostics.Process.Start, but it opens in a new browser tab. Could there possibly be a way to open in the same tab?
So here's the ajax call. This is triggered in a javascript function when the user clicks a button:
$.ajax({
contentType: "application/json",
dataType: "json",
type: "post",
url: "/api/WoApi/PostWoApprGen/" + vUsr,
data: JSON.stringify(invObj),
success: function (res)
{
if (res)
{
var inv = $('#DivInv');
inv.html(res);
output = $('#TmpMsg');
output.html("");
opStatMsg("success", "rptGenWin");
}
else
{
opStatMsg("error", "rptGenWin");
}
}
});
That goes to a class in the controller directory, filename WoApiController.cs:
public string PostWoInv([FromBody] Koorsen.OpenAccess.WrkOrdTemp obj)
{
var currentUser = ClsUtility.GetCurrentUser();
if (currentUser == 0)
{
rep.UpdateWorkOrderStatusInvoiced(obj.WoTempId, currentUser, obj);
}
else
{
System.Diagnostics.Process.Start("~Admin/Login");
}
.............
.............
In your success callback, simply do
location.href = 'Home/Index';
or, preferably, using Razor and a method called Index in HomeController
location.href = '#Url.Action("Index", "Home")';
I am calling a C# function from JQuery but it is giving error.
The JQuery function is written in ascx file and C# function to be called is written in that page's code behind. I am loading the user control into an AJAX tab on tab change event.
Googling, I got that I can not call C# function written in user control. So I written a function in host page(ASPX) and this function is calling my user control function.
But the AJAX request is some how failing, I don't know where. But interesting thing is I have kept a debugger in the error function and I checked the error object.
Status is 200, Status is OK, readyState is 4
and ResponseText is the markup of the page. This means the page is served but the kept the break point in the C# function. It never hits.
I have no idea what's happening. Also this is the first time I am calling a C# function from front end. I don't have detailed idea of what happens under the hood. Please help. Below is the code:
JQuery
$(function () {
$(".hint ul li").click(function () {
// remove classes from all
$(".hint ul li").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
//Ankit J, Implement logic to call jquery
var Availability = this.childNodes[0].innerText.trim();
debugger;
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/CallUCMethodFromJQuery",
data: "{'sAvailability' : 'Availability'}",
dataType: "json",
success: fnsuccesscallback,
error: fnerrorcallback
});
});
});
function fnsuccesscallback(data) {
alert("success-->" + data.d);
}
function fnerrorcallback(result) {
debugger;
alert("error-->"+result);
}
ASPX page's code behind function
[System.Web.Services.WebMethod]
public void CallUCMethodFromJQuery(string sAvailability)
{
MyNamespace.UserControls.ControlName m = new UserControls.ControlName();
m.EditAvailabilityValue(sAvailability);
}
And then the UserControl's code behind
public void EditAvailabilityValue(string sAvailability)
{
}
Sorry for not mentioning.... JQuery is in the User Control because the source of click event is a li element which is in the User Control. Also the UserControl is in a folder UserControls and the host page is in the Pages folder and both these folders are in root folder.
Add contentType: "application/json; charset=utf-8" attribute to your ajax call:
$.ajax({
type: "POST",
url: "../Pages/MyPage.aspx/CallUCMethodFromJQuery",
data: "{'sAvailability' : 'Availability'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: fnsuccesscallback,
error: fnerrorcallback
});
then change EditAvailabilityValue method in the user control to static:
public static void EditAvailabilityValue(string sAvailability)
{
}
and change CallUCMethodFromJQuery method in the aspx page code behind to static so it can be called using jQuery:
[System.Web.Services.WebMethod]
public static void CallUCMethodFromJQuery(string sAvailability)
{
MyNamespace.UserControls.ControlName.EditAvailabilityValue(sAvailability);
}
How can I pass the variable to c# function?.
Suppose that:
<script>
var myValue;
function setValue(idriga) {
myValue = idriga;
}
function getValue() {
return myValue;
}
</script>
This is a script that set and get value. How can i pass the myValue value to a c# function code behind without calling aspx page and passing parameters but passing from aspx to aspx.cs and the from aspx.cs to aspx to show value returned from c# method (example search value into db and return other value?)
My function c# is:
protected string SearchUserByGuid(Guid area) {
return (from us in contextDB.AREAS
where us.ID_AREAS == area
select us.USER_NAME).Single();
}
I'm not sure I entirely understand what you are asking for, but if I do, it's not possible.
What you can do is call a server-side method from JavaScript using AJAX. This server-side method can be a static [WebMethod] or a WebAPI method (if you use ASP.NET MVC or if you have a WebAPI Project).
For more about calling WebMethods with AJAX (and jQuery): http://deebujacob.blogspot.be/2012/01/aspnet-ajax-web-method-call-using.html
For more about Web API: http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
for passing variable to your WebMethod you can use ajax. With Jquery it it will be something like this
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "YourPage.aspx/SearchUserByGuid",
data:JSON.stringify({area: 'YourValueToPass'}),
success: function (dt) { alert(dt);}, //all Ok
error: function () { alert('error'); } // some error
});
also your WebMethod will be public static, so change your method declaration like this
[WebMethod]
public static string SearchUserByGuid(Guid area) {
return (from us in contextDB.AREAS
where us.ID_AREAS == area
select us.USER_NAME).Single();
}
So, I have done this before and made many many ajax calls
For some reason this one doesn't work =(
What do I need to change to get this one to work?
Previously I had an internal server error 500, but after pasting some working code and renaming methods to shorter names finally it changed over to this error of Unknown web method.
Setup
I am using jQuery to make Ajax calls to WebMethods in my Codebehind for my ASP.NET page.
Here is my C# WebMethod
[WebMethod(EnableSession = true)]
[ScriptMethod]
public string viewApps(string foo)
{
string x = "";
//130 lines of useful code.
x = "0";
return x;
}
Here is the Javascript/jQuery doing the ajax call. It is in side a with all my other ajax calls. The other ones work. This one does not. It triggered by an onclick event in the html.
function viewApps() {
var food = "hamburger";
$.ajax(
{
//send selected makes
type: "POST",
url: "MassUpdater.aspx/viewApps",
dataType: "json",
data: "{foo:" + food + "}",
contentType: "application/json; charset=utf-8",
//process the response
//and populate the list
success: function (msg) {
//just for show
},
error: function (e) {
alert(JSON.stringify(e));
$('#result').innerHTML = "unavailable";
}
});
//to be uncommented later when functionality works.
// populateBrakeConfigs();
// populateBedConfigs();
// populateBodyStyleConfigs();
// populateSpringConfigs();
// populateSteeringConfigs();
// populateWheeleBase();
// populateTransmission();
// populateDriveTypes();
function populateBrakeConfigs() { }
function populateBedConfigs() { }
function populateBodyStyleConfigs() { }
function populateSpringConfigs() { }
function populateSteeringConfigs() { }
function populateWheeleBase() { }
function populateTransmission() { }
function populateDriveTypes() { }
}
The ajax error looks like this:
I am also willing to provide any additional code or information about my project upon request.
The answer unfortunately is that somehow the static keyword got left out of the WebMethod, therefore the ajax call cannot find it.
I have a user control that will load via
public static string RenderControl(Control control)
{
var controlWriter = new StringWriter();
var htmlWriter = new Html32TextWriter(tw);
control.RenderControl(writer);
htmlWriter.Close();
return controlWriter.ToString();
}
AJAX used to write the html
$('#testDiv').html(result.d);
This is called through an ajax Post. It loads the user control fine, but since the javascript document load has already fired I cannot use jquery's document.Ready.
My situation is I need to load a user control dynamically and have jquery document.ready fire , or some equivalent. I would rather not use an updatepanel but if that is the only means of getting this done then that is what I will use.
What is an elegant solution to my problem?
You can use the built-in jQuery ajaxStop event to fire when an ajax call completes.
http://api.jquery.com/ajaxStop/
I solved something similar with a custom event that fires after the ajax contents were loaded and displayed.
Trigger the event inside the ajax function, after load and display:
$(document).trigger('ajaxLoadCallback');
And catch it in your document.ready script:
$(document).on('ajaxLoadCallback', function() {
// Your ready functions
}
If you create a function for everything that should be executed after document.ready than you can call this function (e.g. readyFunctions()) on document.ready and after the firing custom event.
public partial class Default : Page
{
[WebMethod]
public static string GetDate()
{
return DateTime.Now.ToString();
}
}
$(function(){
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Do something interesting here.
}
});
});