在 ASP.NET MVC 中,可以使用强类型 radio 按钮来处理表单数据。以下是一个简单的示例:

  1. 在视图文件中,使用Html.RadioButtonFor方法来创建强类型 radio 按钮。例如,假设你有一个名为Gender的属性,可以这样创建 radio 按钮:
@model YourNamespace.YourModel

@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post))
{
    <label>@Html.RadioButtonFor(m => m.Gender, 'Male') Male</label>
    <label>@Html.RadioButtonFor(m => m.Gender, 'Female') Female</label>
    <label>@Html.RadioButtonFor(m => m.Gender, 'Other') Other</label>

    <input type="submit" value="Submit" />
}
  1. 在控制器中,可以通过模型绑定来接收表单数据。例如,假设你有一个名为ActionName的动作方法,可以这样处理表单数据:
[HttpPost]
public ActionResult ActionName(YourModel model)
{
    // 在这里处理接收到的表单数据
    string selectedGender = model.Gender;

    // 返回视图或其他操作
    return View();
}

在这个示例中,YourModel是你的模型类,其中包含一个名为Gender的属性。使用Html.RadioButtonFor方法创建的 radio 按钮会自动与模型的Gender属性进行绑定,当用户选择一个选项时,模型的Gender属性会自动更新为所选值。在控制器的ActionName方法中,你可以通过model.Gender获取用户选择的值。

ASP.NET MVC 强类型 Radio 按钮:表单数据处理指南

原文地址: https://www.cveoy.top/t/topic/fv2l 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录