0
votes

I have a asp.net web app that calls a controller action with the following code:

 $(function () {
        $("#barcode").on("change", function (e) {
            // get the current value
            var barcode = $('#barcode').val();

            // if there's no text, ignore the event
            if (!barcode) {
                return;
            }
           // clear the textbox
            $("#barcode").val("");

           // var holdit = $('#textArea1').val();
            $('#textArea1').val($('#textArea1').val() +' '+ barcode);
             // post the data using AJAX
            $.post('@Url.Action("scanned", "receiveScan")?barcode=' + barcode);
        });
    })

Controller:

 [Produces("application/json")]
[Route("api/receiveScan")]
public class receiveScanController : Controller
{
    private static readonly HttpClient client = new HttpClient();

    public ActionResult scanned(string barcode)
    {

    var test = barcode;
        receiveScanModel newScan = new receiveScanModel();
        newScan.Barcode = barcode;
        newScan.companyNo = 1;

        string jsonScan = JsonConvert.SerializeObject(newScan, Formatting.Indented);

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://notarealservicehere.azurewebsites.net//api/receivescan");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            streamWriter.Write(jsonScan);
        }
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
        }


        return Ok();

Trying to convert to my first Razor page, everything works with the exception (obviously) of the $.post part...

Where would this go?

It is a asp.net core app with razor pages

1
show the conversion so far. most likely you need to use @Url.PageNkosi
I am not sure where to put the code from the Controller, would that go in the .cshtml.cs file as a method. I have a method in that file called public void processScan() {... But just not sure how to actually call it...Joe Ruder

1 Answers

0
votes

Use a handler for example

on your cs file

 public IActionResult OnPostBarcode(string barcode)

on your js var uri = "myPage/?handler=Barcode"

$.post( uri ,{barcode:barcode}, function( data ) {
 console.log(data)
});