can anyone help me in calling my VB.NET method within my javascript function? my method is not shared/static and does not return anything. It just simply saves data to database and redirect the user. PLease help me, Here's my code:
VB method
Public Function SaveVehicles()
Dim res As Boolean
If res = True Then
Dim sModel As String = cboModel.SelectedValue
Dim sVariant As String = cboVariant.SelectedValue
Dim sColor As String = cboColor.SelectedValue
cboModel.SelectedValue = sModel
cboVariant.SelectedValue = sVariant
cboColor.SelectedValue = sColor
Dim oData As New WebServVehSwapping
Dim strSql As String
Dim sDealer As String
Dim sUserName As String
'sDealer = "TBP01"
sDealer = Trim(Request.QueryString("dealercode"))
If sDealer = "" Then sDealer = "TBP01"
sUserName = "User1"
'------------------------------------------
strSql = oData.InsertTblRequirement( _
sDealer _
, Now.ToString _
, sUserName _
, cboColor.Text.Trim _
, cboModel.Text.Trim _
, cboVariant.Text.Trim, "Open")
MsgBox("OKAY")
Response.Redirect("MyRequirements.aspx?DealerCode=" & sDealer)
Else
'do Nothing
End If
End Function
and here's my Javascript function
function ConfirmView()
{
var Ok = confirm('There is/are existing vehicle(s) in Network Vehiches for sale, View Vehicle(s)?');
if(Ok==true)
{
location.href = 'NetworkVehiclesforSale.aspx';
return false;
}
else if (Ok!=true)
{
//THE VB METHOD GOES HERE
}
}
I've tried the callback handler, and it just works with function that return something/string
and i've tried Pagemethod but it just works with static/shared function. please help me, I really need it Badly. PLEasee. Thanks
.Net web services cannot perform magic, i.e. you cannot issue a redirect response to an Ajax request on the server and expect the whole page to be redirected.
The only thing that will happen is that the Ajax call got redirected to another page and tries to get data from there. If you want to change the page in the client browser, you must do it on the client side through JavaScript, e.g. document.location = url_returned_by_your_function_through_ajax_call.
You might want to read "Introduction to Building Windows Communication Foundation Services" - http://msdn.microsoft.com/en-us/library/aa480190.aspx
And especially: "A Guide to Designing and Building RESTful Web Services with WCF 3.5" - http://msdn.microsoft.com/en-us/library/dd203052.aspx
And check out some javascript libraries that make calling RESTful web services easy, like jQuery - http://www.jquery.com/
With jQuery you could make a call to your server-side VB.NET code like this:
$.ajax({
type: "GET",
contentType: 'text/json',
dataType: 'json',
url: "https://URL-TO-SERVICE-HERE/...",
timeout: 10000,
error: function () {
// Deal with the error
},
success: function (data) {
// Do something with the result
// Example:
if (data.dealerCode)
location.href = 'MyRequirements.aspx?DealerCode=' + data.dealerCode;
}
});
Related
So I have created a method on another page of my web app that uses $.Ajax in the Javascript section of my page to retrieve data being returned from a function in my ASP.NET controller for that page/view, and now I am trying to create a new section that will take a parameter being given to the ASP.NET controller from the Javascript script and it will return some data based on the parameter being given.
Here is my Ajax query so far:
function testFunction(){
let selectedDateJS = getSelectedDate()
let customGraphData = $.ajax({
type: "POST",
url: '#Url.Action("GetCustomGraphData", "Graph")',
success: console.log("success: "+success),
})
}
And then here is my controller function in ASP.NET:
public async Task<JsonResult> GetCustomGraphData(string selectedDate)
{
DateTime selectedDateDT = Convert.ToDateTime(selectedDate);
// if selectedDate is NOT a working day:
if (!bh.IsWorkingDay(selectedDateDT)){
// Do something if the date being selected on the form IS NOT a working day.
return Json(null);
}
else// else, if it IS a working day :
{
CustomGraphVM selectedDatedata = await GetCustomData(selectedDateDT);
return Json(selectedDatedata);
}
}
I tried using a data: 'myDate', addition to the Ajax query under the url part but it didn't send anything (null was returned on the string selectedDate parameter of my ASP.NET controller function, but it was returned as null.
Also if it makes it easier, I am parsing a date to the controller from Ajax, and the date is in the format 'yyyy-mm-dd'.
The reason why I am doing this in $.Ajax and with Javascript as opposed to doing it with the ASP.NET is because I am trying to make a dynamic update on the view - and this worked great previously with my GET request that just returned a fixed value from the controller.
If you are passing data via AJAX then you want to match the name you gave your parameter.
function testFunction(){
let selectedDateJS = getSelectedDate();
let customGraphData = $.ajax({
type: "POST",
url: '#Url.Action("GetCustomGraphData", "Graph")',
data: {
selectedDate: selectedDateJs
}
success: console.log("success: "+success),
});
}
In my ASP.NET Core web application, one of my pages has a sequence of steps that it performs to call stored procedures. Depending on whether or not stored procedures return rows, I route to one of two controller actions (either rendering a partial including an additional input, or overriding what that input would do and just coming back to the page on the next step).
Right now I've got code that is nearly there. My controller actions navigate and process correctly and my Ajax works... Sort of.
Button in the Razor view that calls the Ajax function
<input type="button" value="Run Check" onclick="runCheck('#actionItem.StepID', '#Model.Client.DatabaseConnectionString', '#Model.Client.ClientID')" />
Ajax
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (result) {
if (result) {
alert('true');
var stepId = x;
var databaseConnectionString = y;
var clientId = z;
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
alert('false');
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
</script>
Controller Action
public JsonResult ProcessFeedbackHasRows(int StepId, string DatabaseConnectionString, int ClientID)
{
bool hasRows = true;
FeedbackDetails feedbackDetails = new FeedbackDetails();
feedbackDetails.Data = _clientProcessingService.GetProcessingFeedbackDetails(StepId, DatabaseConnectionString);
if (feedbackDetails.Data.Rows.Count == 0)
{
_clientProcessingService.RunProcessStepConfirmation(DatabaseConnectionString, StepId, ClientID, "No information returned, automatically proceeding to next step.");
hasRows = false;
}
return new JsonResult (new { HasRows = hasRows });
}
The alerts are there to just prove that the right condition was in fact met and that the right things are happening. And this is where my problems lie. When I had the Network traffic tab of the F12 tools open, I noticed that whatever json object is created first determines all future runs of the code.
For example: let's say I forced the first item to come through with at least 1 row returned, I'd see the alert true, see the JSON object in the Network tab contain true and see my partial view, as expected.
The next several steps would produce a a false result because no rows were returned from the SP in the controller. The bool in the controller would be set to false, the JSON object in the Network tab would say HasRows = false, but my alert would show true and the partial still renders asking me for confirmation. So despite not returning any rows and producing a false result, I see the alert true and the partial is rendered even though in my Network tab I see
The opposite is true as well. If I had the first item through create an object where HasRows = false, and the next several would have been true, subsequent steps return true in the Network tab, but alert false and go through the false logic in the Ajax.
What is the best way to handle this? Is there a way to clear the JSON or something? I figured by creating a new JsonResult at the end of every method call, it would produce a new result to inspect, but it seems to continue using the first one sent in despite being able to see the others in the Network tab.
What I've tried
Disabling cache in Ajax by adding cache: false, right above the URL in the $.ajax setup.
Resetting the json object within the function after my else braces
result = []; and delete result.hasRows;
Despite these attempts, the ajax will always alert and go through whatever logic flow was sent first while the actual object contains the correct variable.
I actually solved this because in my inexperience with javascript and jQuery, I didn't understand exactly how the logic was being handled since I can't very easily debug the javascript the way I can the C#.
Through trial and error and alerts, I found that essentially, the in my Ajax I had to change the if condition to inspect result.hasRows rather than just the result.
<script type="text/javascript">
function runCheck(x, y, z) {
$.ajax({
cache: false,
url: '#Url.Action("ProcessFeedbackHasRows", "Client")',
type: 'POST',
data: { stepId: x, databaseConnectionString: y, clientId: z },
success: function (result) {
if (result.hasRows) {
alert('result = true');
alert('result.hasRows = ' + result.hasRows);
var stepId = x;
var databaseConnectionString = y;
var clientId = z;
var url = '#Url.Action("ViewProcessingFeedBackPartial", "Client")';
$("#processingFeedbackPartialDiv").load(url, { stepId, databaseConnectionString, clientId },
function () {
$("#confirmButton").removeAttr("style");
});
} else {
alert('result = false');
alert('result.hasRows = ' + result.hasRows);
var newUrl = '#Url.Action("Processing", "Client")';
window.location = newUrl;
}
}
});
};
</script>
The initial question still stands though. Assuming I wanted to delete the entire JSON object and use my initial logic present in the question, how can I clear or delete the entire object so that every time I hit that Ajax call, a new object would be inspected? Or is that now how this works and I solved the problem correctly?
I am able to store the session variable in aspx page using the following way :
$(document).ready(function () {
var userName = "webruster";
'<%Session["UserName"] = "' + userName + '"; %>';
alert('<%=Session["UserName"]%>');
});
now when i am trying to retrieve the Session["UserName"] i am unable to get that value in cs . For this i have a work around but want to know the reason why it is failing ?
Alternative way :
Declaring hidden Variable and Link button
$(document).ready(function () {
var userName = "webruster";
'<%Session["UserName"] = "' + userName + '"; %>';
var x = document.getElementById("<%=hdnsessionvalue.ClientID %>");
x.value = '<%=Session["UserName"] %>';
document.getElementById('<%= lnkButton1.ClientID %>').click();
});
So i am able to retrieve the value in onclick event in server side.
My question :
So why i am unable to retrieve the session value in cs using the first method (i.e without assigning to hidden variable)
If you mean 'client side java script' then you can't, at least not directly. The session data is stored on the server and client side doesn't see it without communicating with server.
To access it can make an HTTP request and have server side modify or return the data.
Updated
Example
<script>
// get the variable
var data = JSON.Stringify(yourVariable);
// Make the ajax call
$.ajax({
type: "POST",
url: "aspPage.aspx/Method", //method we will call
contentType: "application/json; charset=utf-8",
data: {value: data }, //assign the 'data' values to 'value', its the data you want to send
dataType: "json",
success: function (result) {
alert('its working');
},
error: function (result) {
alert('something wrong');
}
});
</script>
on aspPage.aspx
[WebMethod]
public static void Method(string value)
{
sting val = value; // Do whatever you want to
}
You can not set or use Session from javascript directly as it is a Server Side State Management Technique. You should use Hidden Field for that purpose.
Set javascript variable to Hidden Field and in code behind, get the Hidden Field value and set it to your desired Session.
You can achieve it by:
Java Script
$(document).ready(function () {
var userName = "webruster";
var x = document.getElementById("<%=hdnsessionvalue.ClientID %>");
x.value = userName;
document.getElementById('<%= lnkButton1.ClientID %>').click();
});
Code Behind (CS)
protected void lnkButton1_Click(object sender, EventArgs e)
{
string test = hdnsessionvalue.Value;
Session["UserName"] = test ;
}
I need a cross domain web api method to return valid jsonp to some javascript from C#. I can't seem to make this magic happen. I've looked around the web and can't find a start to end example that fits my needs and works... Fiddler shows that I'm returning valid json data but when I hit a breakpoint in F12 dev tools or firebug the result is a failure message.
Here is what I've currently got:
C#
/// <summary>
/// POST: /Instance/RefreshItem
/// </summary>
/// <param name="instanceId"></param>
/// <returns>Json</returns>
[HttpPost]
public System.Web.Mvc.JsonResult RefreshItem(int instanceId, Guid customerId)
{
try
{
var clientConnection = Manager.ValidateInstance(customerId, instanceId);
clientConnection.RefreshItem();
var result = new MethodResult()
{
Success = true,
Value = instanceId,
Message = "Item successfully refreshed."
};
return new System.Web.Mvc.JsonResult() { Data = result };
}
catch (Exception ex)
{
Manager.LogException(_logger, ex, customerId, instanceId);
var result = new MethodResult()
{
Success = false,
Value = instanceId,
Message = ex.GetBaseException().Message
};
return new System.Web.Mvc.JsonResult() { Data = result };
}
}
JS
Example.RefreshItem = function ()
{
Example.SDK.JQuery.getSettings(
function (settings, userId, userLocaleId)
{
alert("Attempting to refresh item for instance " + settings.ConnectionId + "\r\nThis may take awhile.");
var url = settings.SystemUrl + "/Api/WebApiServices/ExampleAdmin/RefreshItem?customerId=" + settings.CustomerId + "&instanceId=" + settings.ConnectionId;
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'RefreshItemCallback',
success: RefreshItemCallback
})
},
Example.SDK.JQuery.defaultErrorCallback
);
}
function RefreshItemCallback(data)
{
alert(data.d.Message);
}
I've also tried $.Post().Always() with the same results.
What am I doing wrong???
I think your problem is that you're instantiating a JsonResult instead of using the Json method.
Presumably the C# method you have is in a controller, so instead of
return new System.Web.Mvc.JsonResult() { Data = result };
do:
return Json(result);
This method probably sets some of the other properties of the JsonResult that, when not set, will not be properly received by the client.
See how Microsoft only shows you how to create a JsonResult via the Json method on MSDN
Note that the same is probably true with methods like View, Content, and File.
Fight all week unable to find an answer until you ask the question somewhere... Within 30 minutes of asking I found this: http://bob.ippoli.to/archives/2005/12/05/remote-json-jsonp/ which was exactly what I needed.
Thanks to all who posted.
I'd like to call a Python function from JavaScript code, because there isn't an alternative in JavaScript for doing what I want. Is this possible? Could you adjust the below snippet to work?
JavaScript code:
var tag = document.getElementsByTagName("p")[0];
text = tag.innerHTML;
// Here I would like to call the Python interpreter with Python function
arrOfStrings = openSomehowPythonInterpreter("~/pythoncode.py", "processParagraph(text)");
~/pythoncode.py contains functions using advanced libraries that don't have an easy to write equivalent in JavaScript:
import nltk # is not in JavaScript
def processParagraph(text):
...
nltk calls
...
return lst # returns a list of strings (will be converted to JavaScript array)
All you need is to make an ajax request to your pythoncode.
You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
From the document.getElementsByTagName I guess you are running the javascript in a browser.
The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.
For example, using jQuery you can do something like:
$.getJSON('http://example.com/your/webservice?param1=x¶m2=y',
function(data, textStatus, jqXHR) {
alert(data);
}
)
You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.
A typical implementation looks like:
#app.route("/your/webservice")
def my_webservice():
return jsonify(result=some_function(**request.args))
You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.
Communicating through processes
Example:
Python: This python code block should return random temperatures.
# sensor.py
import random, time
while True:
time.sleep(random.random() * 5) # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5 # -5 to 15
print(temperature, flush=True, end='')
Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.
// temperature-listener.js
const { spawn } = require('child_process');
const temperatures = []; // Store readings
const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {
// convert Buffer object to Float
temperatures.push(parseFloat(data));
console.log(temperatures);
});
Typically you would accomplish this using an ajax request that looks like
var xhr = new XMLHttpRequest();
xhr.open("GET", "pythoncode.py?text=" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();
You cannot run .py files from JavaScript without the Python program like you cannot open .txt files without a text editor. But the whole thing becomes a breath with a help of a Web API Server (IIS in the example below).
Install python and create a sample file test.py
import sys
# print sys.argv[0] prints test.py
# print sys.argv[1] prints your_var_1
def hello():
print "Hi" + " " + sys.argv[1]
if __name__ == "__main__":
hello()
Create a method in your Web API Server
[HttpGet]
public string SayHi(string id)
{
string fileName = HostingEnvironment.MapPath("~/Pyphon") + "\\" + "test.py";
Process p = new Process();
p.StartInfo = new ProcessStartInfo(#"C:\Python27\python.exe", fileName + " " + id)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
return p.StandardOutput.ReadToEnd();
}
And now for your JavaScript:
function processSayingHi() {
var your_param = 'abc';
$.ajax({
url: '/api/your_controller_name/SayHi/' + your_param,
type: 'GET',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log(error);
}
});
}
Remember that your .py file won't run on your user's computer, but instead on the server.
Despite what some replies and comments suggest, there are a number of ways for using Python on the front-end. For your question in particular, see this reply.