I am working on a C# console application using the Nancy Framework and the Spark view engine, and I am trying to replicate something from another project. However, I am very inexperienced with both Javascript and JSON. To call a chat function in my C# code from my HTML, right now I simply use something like the following...
HTML:
http://localhost:1234/sendchat?message="this is a test message"
C# Code:
Get["/sendchat"] = x =>
{
string message = Request.Query.message;
string message2 = message.Replace("\"", "");
Console.WriteLine(message2);
return View["console.spark"];
};
The problem is that this causes the page to reload. In the project I am looking at for reference, they use Javascript/JSON to call the same type of function without doing a page reload. I understand all of it except for the JSON line as I don't understand what the DataSource is...
$(document).ready(function () {
$("#typechat").keypress(function (event) {
if (event.keyCode == '13') {
event.preventDefault();
message = escape($("#typechat").attr('value'));
$.getJSON(dataSource + "?req=sendchat&message=" + message);
$("#typechat").attr('value', "");
}
});
});
dataSource is just an http domain like http://yourserver.com/possibly/with/a/path. It'll be a string defined somewhere in the code.
JSON resources are fetched just like regular HTML pages, with a normal GET request over HTTP. The only difference is the content is JSON not HTML. Try this in your browser for example to see the JSON returned by the SO api:
http://api.stackoverflow.com/1.1/users/183579
(If you don't have a browser plugin to format/highlight JSON nicely it might just look like a long messy string)
Data source is propobly some web page
dataSource = "http://somepage.com/someaction";
wich renders response as json text, response is grabbed and then parsed to javascript object
Related
Is there a way to get the fully rendered html of a web page using WebClient instead of the page source? I'm trying to scrape some data from the page's html. My current code is like this:
WebClient client = new WebClient();
var result = client.DownloadString("https://somepageoutthere.com/");
//using CsQuery
CQ dom = result;
var someElementHtml = dom["body > main];
WebClient will only return the URL you requested. It will not run any javacript on the page (which runs on the client) so if javascript is changing the page DOM in any way, you will not get that through webclient.
You are better off using some other tools. Look for those that will render the HTML and javascript in the page.
I don't know what you mean by "fully rendered", but if you mean "with all data loaded by ajax calls", the answer is: no, you can't.
The data which is not present in the initial html page is loaded through javascript in the browser, and WebClient has no idea what javascript is, and cannot interpret it, only browsers do.
To get this kind of data, you need to identify these calls (if you don't know the url of the data webservice, you can use tools like Fiddler), simulate/replay them from your application, and then, if successful, get response data, and extract data from it (will be easy if data comes as json, and more tricky if it comes as html)
better use http://html-agility-pack.net
it has all the functionality to scrap web data and having good help on the site
I am new to asp .net and doing some homeproject. Hope you can help!
I have a ASP.NET Web API application with texbox that takes order number as serch string.
I find my object with this code:
var query = ReadFiles()
.Where(n => n.orderNumber == TextBox1.Text)
.Select(n => n);
After that Im trying to convert it to JSON witht his code:
var json = new JavaScriptSerializer().Serialize(query);
TextBox1.Text = json;
I get a String back that says: JSON Visualizer
Now for the question. How do I get this JSON string to the UI, I would like it to show up in some sort of table? I am new to asp .net with that in mind I hope this question is not to stupid. Oh and I use C#
Kind regards.
If you are using a Web API controller class, you can create a method endpoint that returns the data, and then use an Ajax request on the client to that end point.
This is a nice example: Getting Started with ASP.NET Web API 2. You should also look at Routing in ASP.NET Web API to understand the routing mechanism.
In your particular case, you could set up an endpoint to post the order number to from the client's text box (using Ajax). The controller method will then receive the order number as a parameter, and then fetch the data it needs on the server. You would then return the JSON response from that method. The client's success callback function from the post call will receive the JSON response, and then it's up to you to bind that to the markup with JavaScript.
Anyone can help me on how to get the data details from JSON model?
I am using a WCF service which return a JSON type data. It runs well I am sure because I try it from WebClient.
But I want to show the data in my HTML site. I am using the following code, nothing help.
success: function (msg) {
var result = eval("("+msg+")");
$.each(result.UserLoginResult.d,function(i,item){
alert(item.name);
});
It really hurt me, you know.
So I beg your help here, I search from google for hours, No one example can help me. :(.
Thank you all. Finally, I found the problem and fix it.
JQuery already return us Json object not a string, we needn't eval() at all.
Just use msg.d[index][index]!
Happy coding,
Rocky
Did you try the JSON.parse(msg) method?
Then you can simply console.log the answer and find out exactly what to do next.
here is the sample how you do this
$(document).ready(function() {
var jsonp = '[{"Lang":"jQuery","ID":"1"},{"Lang":"C#","ID":"2"}]';
var lang = '';
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
lang += this['Lang'] + "<br/>";
});
$('span').html(lang);
});
out put: jQuery C#
or you can use the $.getJSON method:
So I have a web scraping project where one of the pages has all the necessary content in JSON format inside a set of <script> tags.
here's an example of said <script> tags:
<script>
window.postData = {}
window.postData["content"] = [json content]
</script>
I've used the HtmlAgilityPack to get to the particular <script> tags, but I am not sure how to grab just the json content from this. I can parse the JSON with JSON.net or other library/framework, so I'm not worried about that part. I'm just stuck on getting just the Json. Is there a javascript parsing library or something that I can use to get this, or is there another way to accomplish this.
Any help would be greatly appreciated!
Check out jint
var postDataJSON = new Engine()
.Execute("window.postData = {}; window.postData['content'] = [json content]")
.GetValue("window.postData");
I'm pretty sure this isn't possible but I thought I'd ask...
I have a FileResult which returns a file, when it works there's no problem. When there's an error in the FileResult for some reason, I'd like to display an exception error message on the users screen, preferably in a popup.
Can I do an Ajax post which returns a file when successful and displays a message if not?
I think it is not possible cause in order to handle ajax post, you will have to write a javascript handler on the client side and javascript cannot do file IO on client side.
However, what you can do is, make an ajax request to check if file exists and can be downloaded. If, not, respond to that request negatively which will popup a dialog on client side. If successful, make a file download request.
Not specifically related to MVC but...
it can be done using XMLHttpRequest in conjunction with the new HTML5 File System API that allows you to deal with binary data (fetched from http response in your case) and save it to the local file system.
See example here: http://www.html5rocks.com/en/tutorials/file/xhr2/#toc-example-savingimages
Controller (MyApiController) Code:
public ActionResult DownloadFile(String FileUniqueName)
{
var rootPath = Server.MapPath("~/UploadedFiles");
var fileFullPath = System.IO.Path.Combine(rootPath,FileUniqueName);
byte[] fileBytes = System.IO.File.ReadAllBytes(fileFullPath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "MyDownloadFile");
}
Jquery Code:
$(document).on("click"," a ", function(){ //on click of anchor tag
var funame=$(this).attr('uname'); /*anchor tag attribute "uname" contain file unique name*/
var url = "http://localhost:14211/MyApi/DownloadFile?FileUniqueName= " + funame;
window.open(url);
});