How to pass a javascript variable to server side method - javascript

I am facing issue like I am unable to pass the javascript variable to server side I am aware that it is not achieveable in this scenario so I tried like setting the value to the asp hidden field using jQuery and getting the value of the label in server side but unfortunately I am getting empty value for the hidden field. Help me on how to fix this
CODE
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID){
<%=RenderMethod(DataID) %> // How to pass javascript variable to server side
}
Hidden Field Approach:
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID){
$("#<%=hdnDataVal.ClientID %>").val(DataID);
alert($("#<%=hdnDataVal.ClientID %>").val(DataID)); // Here using javascript I can able to set the value and when I alert the value it is displayed
<%=RenderMethod(hdnDataVal.Value) %> // here the hiddenfield value is empty
}
<asp:HiddenField runat="server" ID="hdnDataVal" />

First of all... you should not mix server code and client code the way you're doing it.
It's a poor way to design your code. Try always to separate client and server code. They execute on different moments, places and under different circumstances... having them together will eventually draw you to difficult to debug errors.
I bet that the problem you're experiencing here is due to this way of coding.
You say on your code snippet that
<%=RenderMethod(hdnDataVal.Value) %> // here the hiddenfield value is empty
When your page is loading and server code is executed the code inside $(document).ready() is not fired yet, as it fires when your whole page finish loading. So, your RenderMethod is firing before you put any value inside the variable.

try using $.ajax();
var url = 'my-url.aspx';
$.ajax({
url: url,
type: 'POST',
data: {'variable_name': my_variable },
success: function(html)
{
alert('ok');
},
});
and receiver on the server-side:
string my_variable = Request.Form['variable_name'];

You can use a Page Method to make a server side call from client side. It's propably the easiest way to accomplish what you want.
First of all you need to include the Script Manager in your aspx page with Page Methods enabled:
<asp:ScriptManager ID="scrmgr" EnablePageMethods="true" runat="server" />
Now you can invoke the server side method and pass it the client side data you want, with sth like this:
<script type="text/javascript">
$(document).ready(function(){
var DataID = "4325";
testDataVal(DataID);
});
function testDataVal(DataID) {
PageMethods.RenderMethod(DataID, OnSuccess, OnError);
}
function OnSuccess(result) {
alert(result);
}
function OnError() {
alert('Some error has ocurred!');
}
</script>
OnSuccess function is invoked in case the server-side method has been succesfully called. Otherwise OnError function is invoked.
This is how the Page Method should be declared inside the .aspx.cs file:
[System.Web.Services.WebMethod]
public static string RenderMethod(string dataID)
{
return "Got here!";
}
If you place a breakpoint inside RenderMethod, then you can verify that client side data (i.e. value "4325") is correctly passed to it.

Related

Pass data from JavaScript function as an object parameter to #Html.Action() C#

Here is what I am trying to do. I want to be able to call an html action and pass in some data as an object parameter. The only thing is this data needs to be returned from a javascript function.
Here is what I am trying to do:
#Html.Action("someAction", "someController", new { passedData = GetDropDownData() })
<script>
function GetDropDownData() {
var data = "test";
return data;
}
</script>
Basically I am trying to pass some drop down data from a control to a partial view being rendered with the #Html.Action(). I want to be able to pass this string to the partial view somehow so I figured I could use JS to pull the drop down data and return it as an object parameter when rendering the page?
Let me know if you have any suggestions or a better way to go about this.
Thank you!
This is not possible the way you're doing it, because razor views are compiled on server side, while javascript is client side. Therefore, the views are already compiled, while javascript runs during runtime. One way to do it is to use ajax to pass variables from javascript to an action in the controller as query parameters or body values. You could achieve that by creating a button or link:
<a href='#' id='clickMe'>Click me</a>
And hooking up jQuery to do the job:
<script>
$(document).ready(function(){
$('#clickMe').click(function(){
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: {
passedData: GetDropDownData()
},
success: function(response){
$('#placeholderForPartialView').html(response);
}
});
});
});
</script>
It would look something like this depending on your method (GET or POST) type.
Here I assume that you return Partial view as a result and replace the contents of #placeholderForPartialView div with the returned view. Please correct me if I'm wrong.

Calling a static method from cshtml file

I'm trying to work on a clickable DIV from some vertical tab panel. What I want is when clicking on a specific DIV call a static method to do some tasks, so I did this:
<div class="tabbable tabs-left">
<ul class="nav nav-tabs">
<li onclick="myEvent()">Tuttle</li>
then, my JavaScript code:
<script>
function clickEvet() {
alert("alert test message");
#MyProject.myMethod()
}
</script>
Calling the function "clickEvent()" works. The problem is that #MyProject.myMethod() is called no matter what, in other words, #MyProject.myMethod() is being executed as soon the page loads. I want it only when I click on my div.
This is from a cshtml file and I'm using .net 4.5
SOLUTION:
I'm editing my question to post the answer for future references...:
Thanks to other comments I finally understood how to work with Ajax and make it work. Here is the solution:
<script>
function vaxGUID() {
$.ajax({
type: 'POST',
url: "/VAXBean/bmx",
data: '{"Name":"AA"}',
contentType: 'application/json; charset=utf-8',
dataType: 'html',
success: function (data) {
bmx = "http://www.vitalbmx.com";
$('a.varURL').attr('href', bmx);
GUID = data;
alert("Good response - " + data + " - " + bmx);
},
error: function (data, success, error) {
alert("Error : " + error);
}
});
return false;
}
</script>
With this Ajax method I'm making the call to some static method in the background
I want it only when I click on my div. <= When you click on the DIV that is being done in the browser after the request has been sent. There is no way for the browser to call directly back inside a method in your application. The HTML has already been generated and sent by the server in the request to the client and that is where that communication cycle stops.
If you want a click (or any other event) to do something specifically on the server you need to do one of these standard actions that are used to communicate back to the server.
Create an AJAX request back to your MVC Controller to get data (or whatever).
Create a link (standard url)
Create a form post back
And of course the #MyProject.myMethod() executes every time your page is rendered because your razor view is a code file that is being interpreted line by line so it can be rendered and sent to the client that requested it. What would be valid here is if myMethod output some javascript or something that the browser could understand and do something with, that is what would be expected.
You can't do it. All # (Razor) expressions is resolved during page rendering on server. That's why you method is called.
Probably, you need to make an Ajax call.
Look for a more detailed explanation here:
How do I call a static method on my ASP.Net page, from Javascript?

passing javascript parameter to asp.net

I have a Javascript function and i want to pass a parameter from javascript to asp.net. my sample code like below:
function ConfirmMessage(message) {
var msg = "<%= Efe.UI.WebApplication.AppCode.HelperClass.GetScreenMessage(message); %>"
alert.confirm(msg);
}
But I am getting error at "message" parameter. The error is:
The "name" does not exist in the current context.
How can I pass parameter from javascript to asp.net?
You cannot pass parameter from javascript to server side at inline code.
You should use jquery ajax for that.
var message = "value";
$.get(
url: "/yoururl/GetScreenMessage",
data: {message : message},
success: function(data){
alert(data);
});
You're trying to dynamically call a server side function with a parameter, but the <%= %> part is actually a Response.Write. So, during the page load the page will try to render with the Efe.UI.WebApplication.*xxx* method's output.
That won't work.
You'll need a different solution all together. Most likely you'll want to use a "REST-like" service call to get the result of the "message" parameter. I would suggest you take a look at AJAX : http://msdn.microsoft.com/en-us/library/bb398874%28v=vs.100%29.aspx and http://www.codeproject.com/Articles/29400/Ajax-Quick-Start-FAQ

Ajax Call Confusion

before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>

ASP.NET AJAX - ScriptManagerProxy and handling html button clicks

I am trying to figure out how to accomplish the following:
Handle client-side click event of button - prevent postback if result of javascript call is false (e.g. onclick="js:return IsThisAllowed()")
Javascript method will return true or false, depending on result of call to generated web service method using ScriptManagerProxy
The code below is simplified down to the main components that I am referring to in this question. I can alert() the return value no problem, but the part I'm having trouble with is how I can return the result of the web service method call back to the button onclick handler? Since the function Finish() is called in a separate thread upon success of what I assume is the XmlHttp.send() call, how can I send the value of the response as the return value of the javascript method? Am I going about this all wrong?
I've used similar code many times before to update the DOM with the return values, such as within a <div>, but never had to worry about capturing the return value and using it within my script.
What I have so far:
.NET web service method (VB.NET):
<WebMethod()> _
<ScriptMethod()> _
Public Function IsAllowed() As Boolean
Return True
End Function
.NET code for the page to generate AJAX web service methods, and html button
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/MyWebService.asmx" />
</Services>
</asp:ScriptManagerProxy>
<asp:Button ID="_btn" runat="server" OnClientClick="js:return IsAllowed();" />
Javascript
<script type="text/javascript">
function IsAllowed(orderid) {
if (!processing) {
processing = true;
var ws = new MyWebService();
ws.IsAllowed(Finish, Error)
// return TRUE if call to IsAllowed returns true!!!
return false;
}
}
function Finish(result) {
alert(result)
}
function Error() {
}
</script>
You can't do this: the call to the web service is an asynchronous request to the server that immediately returns control to the client - and your javascript is (almost) always going to finish executing before the request completes (most likely before the request is even delivered).
Since you don't know when you'll receive the response from the call to ws.IsAllowed, you need to handle it in your callbacks (Finish and Error).
(This is true whatever AJAX mechanism you're using.)
I'm not familiar enough with ScriptManager-based AJAX to tell you exactly how to do this, but the general idea is that I'd turn it around: instead of canceling an ASP.NET button's click event, I'd only trigger the ASP.NET button if the AJAX call returned true.
Using jQuery, I'd do it by making the AJAX call from a vanilla HTML button (not an ASP.NET web control). In the success handler (the equivalent of Finish), I'd trigger my ASP.NET button (which I'd probably hide) when the return value is true.
Have you considered using jQuery?
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "~/WebServices/IsAllowed.asmx/{Method Name}",
data: ('{ whatever data is needed for decision making json serialized }'),
success: function (msg) {
alert(msg);
},
error: function (request, status, error) {
alert(err.Message);
alert(err.StackTrace);
}
});

Categories

Resources