Get href HTML attribute in C#

Asked

Viewed 425 times

1

I have the following code in a Razor view:

<div id="HTMLreturned" class="row">

   @Html.Raw(ViewBag.HTMLreturned);

 </div>

<script>

        var nrLinks = 0;

        $(".enlacesMas > a").each(function(){

            nrLinks++;
            var link = "http://www.meu.site" + $(this).attr('href').replace("..","");

            // Agora preciso de guardar todos os link num array ou algo do género


        });


</script>

In the controller put in the Viewbag.Htmlreturned the result of this line:

ViewBag.HTMLreturned = WebClient.client.DownloadString(meuUrl)

How can I run my code view in my controller to keep each href in variable C#?

Obs:

The html which jQuery works with is rendered before the script is executed, so these classes are from html within the viewbag

  • 1

    What do you mean, young man? Explain better what you want to do.

  • @jbueno I think it’s clearer now

  • After running each, you want to store all href in an array and return it to a controller. This?

  • @Aline, I don’t want to have a viewat all, I want to do it all in controller

  • Yeah, I didn’t quite understand.

  • I realized now that what I wanted to do is not going to be possible, basically what I need now to turn this jQuery code into code c#

  • Can you explain why you wanted to use backend code instead of Jquery? What was your use case?

  • I had a string that was an html, and I wanted to extract information from it using a language like jQuery, because I already know some techniques

Show 3 more comments

1 answer

4


I was able to get exactly the same result in C# by installing the Csquerylatest with Nuget, and writing the following code:

 string htmlCode = "";
        List<string> links = new List<string>();

        using (WebClient client = new WebClient())
        {
            htmlCode = client.DownloadString("https://www.boe.es/buscar/anboe.php?campo%5B0%5D=TIT&dato%5B0%5D=&operador%5B0%5D=and&campo%5B1%5D=ID_DEM&dato%5B1%5D=&operador%5B1%5D=and&campo%5B2%5D=DOC&dato%5B2%5D=&operador%5B2%5D=and&campo%5B3%5D=ID_TIP&dato%5B3%5D=&operador%5B3%5D=and&campo%5B4%5D=GEO&dato%5B4%5D=&operador%5B4%5D=and&campo%5B5%5D=DOC&dato%5B5%5D=&operador%5B6%5D=and&campo%5B6%5D=FPU&dato%5B6%5D%5B0%5D=02%2F01%2F2017&dato%5B6%5D%5B1%5D=02%2F01%2F2017&page_hits=200&sort_field%5B0%5D=FPU&sort_order%5B0%5D=desc&sort_field%5B1%5D=ref&sort_order%5B1%5D=asc&accion=Buscar");
            var query = CQ.Create(htmlCode);
            var rows = query[".enlacesMas a"];
            foreach (var row in rows)
            {
                var newLink = row.Attributes["href"];
                links.Add(newLink);
                // aqui guardo todos os link numa lista
            }

        }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.