How do I pass a list from aspx to javascript? - c#

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!

Related

Ajax to WCF Service

I am having a WCF Service (Ajax-enabled) and I need to call its methods using AJAX. The WCF Service name is NameService.svc and it is located within a WebService folder at the root directory of the Website. Here is how things work: I have to create a user control which includes a table layout containing the text fields to collect the user data and when clicking the button I need to use jQuery and Ajax to call the methods which will insert the data to the database. I tried the following code but it did not work for me and I need to know what I am missing or wrote incorrectly within the user control:
$(function() {
$('button').click(function() {
var name = $('text').val();
$.ajax({
url : 'NameService.svc/InsertData',
data : { suppliername : name },
method : 'post',
datatype : 'json',
success : function(data) {
alert(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table">
<tbody>
<tr>
<td>Supplier Name:</td>
<td><input type="text" name="sname"></td>
</tr>
<td colspan="2"><button type="button" class="btn btn primary">Insert</button></td>
</tbody>
</table>
Note I am using Bootstrap within my project. Is there a problem using the button element instead of input element with type as submit? What have I missed in the url of the ajax call? Should the method within the WCF Service be decorated with specific attributes? If I will call a method that will return only data should I use the data property within the Ajax call or ignore it also the method will be post to or it should be get in that way.
If you are doing $.ajax for http post and get. I will recommend you watch the tutorial from https://www.udemy.com/rest-wcf-service-in-aspnet/learn/v4/t/lecture/5225772
After you retrieve the data, you can do a database connection from svc.cs and import these data(s) to your database. I assume you have already know how to do database connection. If no, just do some online search, you probably will learn that.
However, I have no clues if your data is in nested json format. I am struck at there also... sighh

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

MVC C# Code in Javascript

On a cshtml page in my View i easily get the URL to an action with thise line:
<h1>#Url.Action("NewComment", "Case")</h1>
And if I write this in Javascript:
<script>
alert('#Url.Action("NewComment", "Case")');
</script>
It also comes up correct in the alert.
However my problem is that at the bottom of the page I have several other javascript beeing referenced like this:
<script src="~/Scripts/custom/SomeScript.js"></script>
And if I write alert('#Url.Action("NewComment", "Case")');
In that file. It just comes up as #Url.Action("NewComment", "Case") in the alert box.
So how come it doesn't work in this file?
In the same file I also have a click method with $.ajax({ method and the url is referenced like this: url: '#Url.Action("NewComment","Case")', and here it works fine again.
So how come it works here again? Is it something with that Ajax method is a Jquery Object??
The spesific problem I have is that I need to reference the URL.Action method i the Ajax call of a Jquery Datatable.
var table_comment= $('#comment_table').dataTable({
"sDom": "<'dt-toolbar'>",
ajax: {
url: "/Case/NewComment/", //This works but want to change it to use URL Action
url: '#Url.Action("NewComment", "Case")', //don't understand why this doesn't work
type: "POST",
data: {"id": Case_ID }
},
The reason that #Url.Action("NewComment", "Case") works in *.cshtml, is that it is rendered to HTML on the server by ASP.NET MVC. As for your *.js files, these are not transformed by ASP.NET MVC, so what you see is what you get.
Specifically, .cshtml files are C# Razor templates, which get rendered by ASP.NET MVC to .html files.
As for your .js files, perhaps you could work around this by defining your URLs as global variables in your .cshtml, which you simply refer to in your .js files.
<script>
var newCommentUrl = '#Url.Action("NewComment", "Case")';
</script>
You cannot write Razor syntax inside separate js file because after all its Razor syntax '#' which only
Razor engine could interpret(and could be written inside .cshtml extension Pages only) and razor engine
convert it to appropriate HTML so that is why
in separate js file file when you write alert("#Url.Action("NewComment", "Case")") it comes as
#Url.Action("NewComment", "Case")
You can't have razor syntax ( #Url.Action ) inside a linked JavaScript file - Visual Studio doesn't work like that.
As a solution, write out your variables in javaScript in your CSHTML file like so:
<script type="Text/javascript">
var dataTableURL = '#Url.Action("NewComment","Case")';
</script>
And then underneath this reference your external javascript file
<script src='#Url.Content("~/Scripts/MyJavaScriptFile.cs")' type="text/javascript"></script>
And modify your javscript variable to use the above variable:
var table_comment= $('#comment_table').dataTable({
"sDom": "<'dt-toolbar'>",
ajax: {
url:dataTableURL,
type: "POST",
data: {"id": Case_ID }
},
I found out a way better solution for this!
RazorJS :) Works perfect.
http://www.nuget.org/packages/RazorJS

Create new Script within <div> from C# and Reload newly created Script

I would like to implement the following, which would appear to be fairly easy, but I have been searching for a working example without success.
i) I have an HTML Tag in an aspx Page with an identification:
<div id="demo" runat="server">
ii) This Tag contains the following Script Tag, which itself has an identification:
<script id="scriptdemo" type="text/javascript" src="http://www.myurl.com/myquery"></script>
iii) I have an AJAX call which calls a Server Function (which is working without any issue)
iv) From that Server Function, I would like to either modify the “src” Attribute of the Script, or create and insert a new script in the existing division with a new src if this solution is easier to implement.
v) After executing the Server Code contained within the Server Function, the flow is properly passed back to the client (here again, I do not have any issue with this process).
vi) Once back on the client, I would like to refresh/reload the newly created script (or updated src attribute) using JavaScript/AJAX (either standard Javascript or JQuery).
Would someone have a working example of such code?
Check out http://api.jquery.com/jQuery.getScript/
It's basically shorthand for $.ajax with datatype as "script". This will load a script file for you, and give you the chance to run a callback when it's done.
$.ajax({
url: "your/ServerMethodThatReturnsScript",
dataType: "script",
success: successCallback
});
becomes
$.getScript("your/ServeRMethodThatreturnsScript", function() { /* some success callback */ });
In the event you can't do this but CAN make an ajax call to your server, you can use the eval method to execute any string that is in the form of javascript:
eval("/*some javascript*/");

How to Get JavaScript value From c# back end

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>

Categories