How to Get JavaScript value From c# back end - c#

Hi guy i have a javasciprt will create a value , is that any way for me to capture the value in my c# back end code.
function GetKey(){ return Key; } //key is a combination value
Thank you

C# in backend
public String MyVariable;
MyVariable = "Some Value";
ASPX
<%=MyVariable %>

via ajax
You can put it into your aspx page code and pass it to your js (if you are using asp).
If Key is an object, you can serialize it to json string and use JSON parser to deserialize it. If it is a basic type, use <%= Key %> in your asp page is OK. (Note you cannot put the code in your js file)
<script type="text/javascript">
var key = JSON.parse('<%=JsonConvert.SerializeObject(someObj.GetKey()) %>');
//now you can use key in your js logic
</script>

Related

How do I inject javascript code via webview?

Basically what I want to do is this this but I can't seem to find something similar for webview XAML control. What I ultimately need to do, is capture an incoming json file from the webview. As is, I get a bad request from the server and unsupported file exception from the webview. I thought about injecting a javascript so that it would alert me, I could get the body of the incoming json and bypass all the errors.
There are two main things you can do:
Call functions programically
Inject any code by using the HTML string
Function Calling
You can use InvokeScript to call javascript functions.
If you have in a webpage with a script:
<script lang="en-us" type="text/javascript">
function myFunction() {
alert("I am an alert box!");
}
</script>
Then you can in C# call:
MyWebview.InvokeScript("myFunction", null);
Which will execute the script function myFunction.
Injecting Text
If you download the HTML page and all other needed files(using the Windows HttpClient), you can inject any code by manipulating and then Navigating to string.
Lets say you want to change the above script to add another function, "HelloWorld", then you can
Search the file for something you know will be there, such as: <script lang=\"en-us\" type=\"text/javascript\">
Using string manipulation, add the desired text, such as a function (but this can be anything)
Navigate to the String
The C# code:
string MyWebPageString = GetWebpageString(WebpageUri);
string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
int IndexOfScriptTag = MyWebPageString.IndexOf(ScriptTagString);
int LengthOfScriptTag = ScriptTagString.Length;
string InsertionScriptString = "function SayHelloWorld() { window.external.notify(\"Hello World!\");} ";
MyWebPageString = MyWebPageString.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
MyWebview.NavigateToString(MyWebPageString);
The result will be that the navigated to Webpage will look like this:
<script lang="en-us" type="text/javascript"> function SayHelloWorld() { window.external.notify("Hello World!");}
function myFunction() {
alert("I am an alert box!");
}
</script>
Since the injection can be applied to any area, even the HTML, you should be able to figure something out.
Hope this helps. Good luck.
This answer was based on this MSDN blog

Jquery get property from C# has warning in visual studio 2012

I have a property in the aspx.cs page:
public string UtilizatorLogat
{
get
{
return (!(Session["utilizator"] == null)).ToString().ToLower();
}
}
And I get it in the aspx page, on $(document).ready:
utilizatorLogat = <%=UtilizatorLogat%>;
But visual studio says: Syntax Error.
I cannot include it in "" because it's a boolean value and I don't want to make it a string one...
Any ideas why is this warning shown?
It's a syntax error to the JavaScript parser, which doesn't think <%=UtilizatorLogat%> is valid. This is a common problem when mixing client/server code.
One way you can work around this is to quote the value, but then parse or test it (in JavaScript) to a boolean.
var utilizatorLogat = /true/i.test("<%=UtilizatorLogat%>");
When the page renders, it will be:
var utilizatorLogat = /true/i.test("false");
It looks strange, but this way you avoid syntax errors in the designer which can also cause problems with automatic formatting.
You need to convert it to string if you want to use it with on client side
var utilizatorLogat =<%=UtilizatorLogat.ToString().ToLower()%>;
You can use this trick too to avoid warnings:
original code:
<script type="Text/javascript">
<%If Page.IsPostback Then%>
alert("my javascript code");
<%End If%>
</script>
solution:
<script type="Text/javascript">
//<%If Page.IsPostback Then%>
alert("my javascript code");
//<%End If%>
</script>
Reference: Visual Studio confused by server code inside javascript
I think is a mix between Adriano and Phx answer (Adriano don't put the quotes)
I use always this kind of solution and it works
var utilizatorLogat ='<%=UtilizatorLogat.ToString().ToLower()%>';

#Url.Action inside $.get

I've seen a few posts about this but stills couldn't understand why this is not working
$.get('#Url.Action("Edit","Contacts")', {id: parseInt($(this).attr('id')) } , function (result) {
obviously this does
$.get("/Contacts/Edit/" + parseInt($(this).attr('id')), function (result) {
I've tried with replacements and still getting the proper id but the #Url.Actions appears as a string itself generating weird routes as this one for the former code, seems to me that the url.action is not executed, right?
localhost:53720/#Url.Action(Edit,%20Contacts)?id=23918
Edition: Actually the route generated for that code is
localhost:53720/Url.Action(%22Edit%22,%20%22Contacts%22)?id=23918
the other is for another try I've made
Anyone can tell me why?
Thanks
To have access to HtmlHelpers inside javascript, the javascript code must be inside a View page, and not inside a javascript file
<script>
var url = '#Url.Action("Edit","Contacts")';
console.log(url);
</script>
Looks like #Url.Action is not getting called and the URL is not being returned.
var url = '#Url.Action("Edit","Contacts")';
$.get(url, {id: parseInt($(this).attr('id')) } , function (result)
If JS complains about the above, you can try specifying #: beforehand to let razor take control.

Parsing javascript HTML using HTMLAgilityPack

I have the following HTML that I'm trying to parse using the HTML Agility Pack.
This is a snippet of HTML code:
<body id="station_page" class="">
...
<div>....</div>
<script type="text/javascript">
if (Blablabla == undefined) { var Blablabla = {}; }
Blablabla .Data1= "I want this data";
Blablabla .BlablablaData =
{ "Data2":"I want this data",
"Blablabla":"",
"Blablabla":0 }
{ "Blablabla":123,
"Data3":"I want this data",
"Blablabla":123}
Blablabla .Data4= I want this data;
</script>...
I'm tring to get those 4 data variable (Data1,Data2,Data3,Data4). first, I tried to found the javascript:
doc.DocumentNode.SelectSingleNode("//script[#type='text/javascript']").InnerHtml
How can I check if it's really the right javascript?
After finding the relevant javascript how can I get those 4 data variable (Data1,Data2,Data3,Data4)?
You can't parse javascript with HTML Agility Pack, it only supports HTML parsing. You can get to the script you need with an XPATH like this:
doc.DocumentNode.SelectSingleNode("//script[contains(text(), 'Blablabla')]").InnerHtml
But you'll need to parse the javascript with another method (regex, js grammar, etc.)

How do I pass a list from aspx to javascript?

I have a list that I loop through to populate my table. I would like to pass a row of data to my javascript code at best. If not, I would like to pass the list and the id number to search for that row in the list. How can I do this?
<%foreach(var item in Model.NewList) { %>
<tr>
<td><%=item.EntryDate.ToShortDateString() %></td>
<td onmouseover="showDetailsHover(<%=item %>,<%=item.idNumber%>);"
onmouseout="hideDetailsHover();"><%=Html.ActionLink(item.idNumber,"SummaryRedirect/" + item.idNumber) %></td>
</tr>
<% } %>
You can use Json serialization to pass this data
http://json.codeplex.com/ - library for serialization
The concept of "passing a list from aspx to javascript" is a little hard to understand since your ASP.NET code runs on the server and javascript code runs in the browser. Because they exist in different domains, you can't simply "pass" a list from one domain to the other.
However, you have several options available:
Expose a web service that you can access from javascript. The web service can be responsible for providing the row of data so that javascript can understand it.
Put staticly formatted JSON data directly into your javascript function when your page loads. JSON is a format that javascript can understand. While technically this isn't "passing" a variable into a javascript function from ASP.NET, it is saying "Here's the data I want to run in my javascript function when/if it runs on the client."
The quickest way I can think of is this:
Use Json.Net to serialize your list as json string on your page.
Include jQuery and jQuery-json plugin.
Define a javascript list in a javascript function.
Something like this on your aspx page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://jquery-json.googlecode.com/files/jquery.json-2.2.js"></script>
<script type="text/javascript">
function foo() {
// This is where we use the Json.Net library
var rawJsonString = '<%= Newtonsoft.Json.JsonConvert.SerializeObject(Model.NewList) %>';
// This is where we use the jQuery and jQuery-json plugin
var list = $.evalJSON(rawJsonString);
// Do stuff with your list here
}
</script>
THanks for the ideas. I eventually dug a little deeper with your suggestions and I used a for loop on the list I passed then add my data to the row based on the loop...
success: function(data) {
var loopList = data.message.NewList;
for (var i = 0; i < loopList.length; i++) {
addRecentData(loopList[i]);
}
},
});
function addRecentData(data) {
....
}
THanks for the nudge!

Categories