Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

asp.net - Getting value from html radio button - in aspx-c#

I have the following HTML source

<form name="Register1" action="Register.aspx" id="registerform" method="post" 
      runat="server" style="margin-top: 15px;">
    <input type="radio" name="Gender" value="male" />male
    <input type="radio" name="Gender" value="female" />female
</form>

My question is how can I get the selected value to variable in the c# page?

I tried this :

Gender = Request.Form["Gender"].ToString();

But it didn't work...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

place your code like this:

 if (Request.Form["Gender"] != null)
 {
     string selectedGender = Request.Form["Gender"].ToString();
 }

Note that Request.Form["Gender"] will be null if none of the RadioButtons are selected.

see the markup below

<form id="form1" runat="server" method="post">
    <input type="radio" name="Gender" value="male" id="test" checked="checked" />
    male
    <input type="radio" name="Gender" value="female" />female
    <input type="submit" value="test" />
    <asp:Button ID="btn" runat="server" Text="value" />
</form>

for both the buttons i.e input type="submit" and usual asp:button, Request.Form["Gender"] is going to have some value upon PostBack, provided, either of the RadioButtons is selected.

And yes, upon PostBack only, i.e. when you hit either of the buttons and not on first load.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...