gpt4 book ai didi

asp.net-mvc-3 - ASP.Net MVC 页面提交时如何捕获选中的单选按钮

转载 作者:行者123 更新时间:2023-12-02 02:18:37 24 4
gpt4 key购买 nike

这是我的代码,它显示我的模型中的两个单选按钮。主要问题是当我提交表单时,当我在表单提交之前选择一个单选按钮时,模型性属性变得为空。请帮我找出问题所在。

模型类

public class StudentModel
{

[Required(ErrorMessage = "First Name Required")] // textboxes will show
[Display(Name = "First Name :")]
[StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
public string FirstName { get; set; }

[Required(ErrorMessage = "Last Name Required")] // textboxes will show
[Display(Name = "Last Name :")]
[StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
public string LastName { get; set; }

[Required(ErrorMessage = "Sex Required")]
[Display(Name = "Sex :")]
public int SexID { get; set; }

public List<Sex> Sex { get; set; }

}

public class Sex
{
public string ID { get; set; }
public string Type { get; set; }
}

Controller 类

public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
var student = new StudentModel
{
FirstName = "Rion",
LastName = "Gomes",

//I think the best way to populate this list is to call a service here.
Sex = new List<Sex>
{
new Sex{ID="1" , Type = "Male"},
new Sex{ID="2" , Type = "Female"}
}
};

return View(student );
}

[HttpPost]
public ActionResult Index(StudentModel model)
{
if (ModelState.IsValid)
{
//TODO: Save your model and redirect
}

//Call the same service to initialize your model again (cause we didn't post the list of sexs)
return View(model);
}
}

查看代码

@model MvcRadioButton.Models.StudentModel

@Html.BeginForm()
{
<div>
@Html.LabelFor(model => model.FirstName)
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
<div>
@Html.LabelFor(model => model.LastName)
@Html.EditorFor(model => model.LastName)
@Html.ValidationMessageFor(model => model.LastName)
</div>
@{
foreach (var sex in Model.Sex)
{
<div>
@Html.RadioButtonFor(model => model.Sex, new { id = "sex" + sex.ID })
@Html.Label("sex" + sex.ID, sex.Type)
</div>
}
}

<input type="submit" value="Submit" />
}

如果可能,请运行我的代码并告诉我如何实现我的目标,如果有人认为这种情况可以以更好的方式处理,只需更改代码,然后请告诉我,因为我是 MVC 的新手。

最佳答案

View 模型

public class StudentModel
{
//properties
public bool Sex { get; set; }
}

查看

@using (Html.BeginForm())
{
@Html.RadioButtonFor(model => model.Sex, "false", new { id = "male" })
@Html.Label("male", "Male")

@Html.RadioButtonFor(model => model.Sex, "true", new { id = "female" })
@Html.Label("female", "Female")
<button type="submit">OK</button>
}

Controller

[HttpPost]
public ActionResult Index(StudentModel model)
{
//you can modify "model" however you want here
return Content("Sex: " + model.Sex);
}

关于asp.net-mvc-3 - ASP.Net MVC 页面提交时如何捕获选中的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18911433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com