user12225397
user12225397

Reputation:

HtmlAgilityPack How to get a SELECTED <option> in a <select>

So im trying to get the selected Value from a selectfield.

The Html:

<select class= "c_selectfield" id="id_secMode-101" name="secMode-101"><option value="1" >None</option><option value="2" >WPA_PSK_TKIP</option><option value="3" >WPA2_PSK_AES</option><option value="5" SELECTED >WPA2-EAP</option><option value="4"  >WEP</option><option value="7"  disabled>Advanced config</option></select>

In this Example WPA2-EAP is selected and i want the Programm to return the Value 5.

My C# function looks like this:

        public void Get_Wlan_Settings_Html(HtmlDocument html)
    {

        SSID = html.GetElementbyId("id_Setssid-101").GetAttributeValue("value", "");
        PassKey = html.GetElementbyId("id_wlanMgr_fakePassKey-101").GetAttributeValue("value", "");
        client_user_id = html.GetElementbyId("id_userId-101").GetAttributeValue("value", "");
        eap_PassKey = html.GetElementbyId("id_wlanMgr_fakeEapPwd-101").GetAttributeValue("value", "");

    }

the elements i'm getting are in the same html, these work perfectly fine. But How can i get the selected Values?

Upvotes: 1

Views: 1682

Answers (2)

Finch Wang
Finch Wang

Reputation: 92

You can code like this,

var selectedValues = html.GetElementbyId("id_secMode-101")
                         .ChildNodes
                         .Where(x => x.GetAttributeValue("selected", string.Empty) == "selected");

Upvotes: 0

EylM
EylM

Reputation: 6103

You can get the selected option value for id_secMode-101 by using XPath.

html.DocumentNode.SelectSingleNode("//select[@id='id_secMode-101']//*[@selected='selected']").
Attributes["value"].Value;

More info regarding SelectSingleNode.

Upvotes: 1

Related Questions