Display JSON into html table c# - c#

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.

Related

How do I get the Status Code and Header data from a HttpResponseData object?

I currently have a Blazor Client (Wasm) with a ASP.NET Core Web API. (Both deployed to Azure)
The ASP.NET Core Web API returns a IActionResult, which converts into a HttpResponseMessage in my BlazorClient.
I wanted to swap out my ASP.NET Core Web API with a Azure Function HTTP Trigged.
The Azure Function is .Net 5. (I had to do this since all of my other projects in the solution is .Net 5).
Since the function is written in .Net 5, a HttpResponseData Object is returned.
In my HttpResponseData object I have Status Code which I want to test in my Client, Header Data, which I need to access (Total Count), plus the Body that has my list of data.
When I call the Azure Function from my Blazor Client, I can't access the Header data.
I was also having issues getting the Body data as well when I use the _httpClient.GetAsync method.
The best I could do was use the _httpClient.GetStringAsync method. That get me my data from the body.
But, I want the Status Code and Header Data as well.
See the code below.
public async Task<string> GetVpbDelegatesAsync2(int? pageNo, int? pageSize, string searchText)
{
var requestUri = $"{RequestUri.VpbDelegates}?pageNo={pageNo}&pageSize={pageSize}&searchText={searchText}";
var response = await _httpClient.GetAsync(requestUri);
//This line throws an exception. If I comment it out. I get my Body data
var total = response.Headers.GetValues("X-TotalCount").First();
return await _httpClient.GetStringAsync(requestUri);
}
So my questions are:
How can I get that Status Code?
How can I get my Body Data?
How can I get my Header Data
Does anyone know of any demos / code examples with a client that calls a Azure Function that returns HttpResponseData. (I can't find any examples.)
Thanks for your help.
Edit: Just for those keep track at home:
I am able to get the Status Code, but I still can't get the Header Data. I made the same call in PostMan and Header data is there.
Edit 2: I figured out how to get my data out of the Body / Content. But still not getting Header data.
The HttpResponseData object is only in the context of the function code. Your HttpClient object would still return HttpResponseMessage like #Greg mentioned.

Call an external webservice from within a .NET Core Web API POST method

I am currently creating a simple game that can be played from the Postman console, as a .NET Core Web API project.
I can POST data to the game from Postman without difficulty but I'm having some problems setting up a call to an external webservice at the point at which the POST is made.
What I want to do is receive a POST, and then make an external API call for some random numbers from an external service that provides random numbers.
This method would seem to need to be inside the POST method to ensure that it's triggered after each POST request and generates new numbers each time.
I have created a ProcessRandomNumbers asynchronous method using HTTPWebClient that returns a value of 'msg' (message) and then I am trying to call that method in my POST, then pars the string to numbers and assign the values and use them for calculations. However, I can't seem to access the data ('msg') returned from the method inside of my POST request?
The code inside my POST method is below:
await ProcessRandomNumbers();
if (diceRoll.Roll == true)
{
diceRoll.DiceRoll = msg;
}
Thanks for any help anyone can provide!
Looks like ProcessNumbers() only trying to get the numbers from external website, so this method can be renamed as GetRandomNumbers().
Here is the code snippet where I returned the API response back to caller:
private async Task<string> GetRandomNumber()
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("User-Agent",
".NET Foundation Repository Reporter");
return await client.GetStringAsync("https://www.random.org/integers/?num=2&min=1&max=6&col=2&base=10&format=plain");
}
In the caller assign the return value to msg field, and use it.

How to send json using GET method to REST like API

I must implement method in my application which will send some data (which according to api documentation should be JSON) using GET method (it is weird...). How I can do this using c sharp in windows 8 (RestSharp lib is not working there). I don't have any experience in REST clients but I have already implement other features but there data was sended by POST or DELETE methods. I have tried "tranlate" json to get like this:
JSON:
{
a = "foo",
b = "bar
}
GET URL:
__SITE__?a=foo&b=bar
But server return null values (not error). I don't know how to deal with this thing :/
Thanks for help in advance :)
If you have api you have name of param that you should send. Just convert the data into json and sind is as this param.
If you have to send json why you`re sending param a and b as 2 diffrent strings ?
remember that a GET method can be invoked by HttpClient. Just invoke the URL
Finally it turned out (in my case) that API also accepts providing data in that way: URL?a=foo&b=bar regardless of the fact that it should be json.
Long story short, I think this will be most illuminating .. it "fills in the blanks" with using HttpClient to fire JSON Formatted data at a REST API
How do you set the Content-Type header for an HttpClient request?

POSTing to an ASP MVC 4 site from a C# Windows application

I'm writing a Windows application that will communicate with an ASP MVC site.
The site has a controller method for POST requests that passes to it an object from my Model.
I have access to those same classes in my desktop application and was hoping that I would be able to create an object of the same type, then create an HTTP POST request, attach the object and send it to the site.
I found that the POST data is just key-value pairs that match the properties of the class so Property1=value1&Property2=value2 worked, however I'm stumped as to how to represent a list.
Is there some easy way to serialise the object into an HTTP request or would I have to make multiple requests for each item in the list?
You can use WebClient to implement such behavior
string url = "your POST action url here";
NameValueCollection formData = new NameValueCollection();
formData["name"] = "John";
// add more form field / values here
WebClient webClient = new WebClient();
byte[] responseBytes = webClient.UploadValues(url, "POST", formData);
string response = Encoding.UTF8.GetString(responseBytes);
However, this is not good practice. This kind of communication should be implemented with web services - if your application is designes well (for example you have service layer/repository), there is nothing easier than expose simple webservice side by side with MVC frontend.

What is a JSON Data Source?

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

Categories

Resources