在 ASP.NET Web Pages 中,表单是与用户交互的关键部分,用于收集用户输入数据。Web Pages 使用 <form> 元素来定义表单,而在表单中,可以包含各种输入元素(如文本框、复选框、下拉列表等)以及用于提交表单数据的按钮。以下是 ASP.NET Web Pages 中使用表单的基本示例:

1. 表单基本结构:
<!DOCTYPE html>
<html>
<head>
    <title>Form Example</title>
</head>
<body>

    <h2>Simple Form</h2>

    <form method="post" action="ProcessForm.cshtml">
        <!-- 表单内容将在这里添加 -->
        
        <input type="submit" value="Submit Form" />
    </form>

</body>
</html>

在上面的示例中,我们使用了 <form> 元素来定义表单,指定了表单的提交方法 (method="post") 和提交的目标页面 (action="ProcessForm.cshtml")。在表单中,我们添加了一个提交按钮 (<input type="submit" />)。

2. 添加表单元素:

在 <form> 元素中,你可以添加各种表单元素来收集用户输入。以下是一些常见的表单元素:

  •  文本框 (<input type="text">):
  <label for="username">Username:</label>
  <input type="text" id="username" name="username" />

  •  密码框 (<input type="password">):
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" />

  •  复选框 (<input type="checkbox">):
  <input type="checkbox" id="subscribe" name="subscribe" value="yes" />
  <label for="subscribe">Subscribe to Newsletter</label>

  •  单选按钮 (<input type="radio">):
  <input type="radio" id="male" name="gender" value="male" />
  <label for="male">Male</label>
  
  <input type="radio" id="female" name="gender" value="female" />
  <label for="female">Female</label>

  •  下拉列表 (<select>):
  <label for="country">Country:</label>
  <select id="country" name="country">
      <option value="us">United States</option>
      <option value="ca">Canada</option>
      <option value="uk">United Kingdom</option>
  </select>

3. 处理表单提交:

在表单中添加了元素后,你需要处理用户提交的数据。可以创建一个目标页面来处理表单提交,例如 ProcessForm.cshtml,并在表单的 action 属性中指定该页面。
<!-- ProcessForm.cshtml -->

@{
    var username = Request["username"];
    var password = Request["password"];
    var subscribe = Request["subscribe"];
    var gender = Request["gender"];
    var country = Request["country"];
}

<!DOCTYPE html>
<html>
<head>
    <title>Form Submission Result</title>
</head>
<body>

    <h2>Form Submission Result</h2>

    <p>Username: @username</p>
    <p>Password: @password</p>
    <p>Subscribe: @subscribe</p>
    <p>Gender: @gender</p>
    <p>Country: @country</p>

</body>
</html>

在目标页面中,使用 Request 对象来获取表单提交的数据。在上面的例子中,我们获取了用户名、密码、订阅状态、性别和国家的值,并在页面中显示了这些值。

以上是一个简单的 ASP.NET Web Pages 表单的基本示例。实际项目中,你可能需要添加验证、处理更复杂的表单逻辑以及将数据保存到数据库等操作。


转载请注明出处:http://www.pingtaimeng.com/article/detail/14688/ASP.NET