【发布时间】:2019-11-23 06:43:08
【问题描述】:
我在项目 Asp.net MVC5 上有一些代码: 型号
public class Question
{
public int? ID { get; set; }
public string name { get; set; }
}
public class Answer
{
public int? ID { get; set; }
public string Answer1 { get; set; }
public string Answer2 { get; set; }
public int? QuestionID { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
List<Question> questions = new List<Question> {
new Question { ID = 1, name = "What is the capital of Germany" },
new Question {ID =2 , name ="What is the capital of France" }
};
List<Answer> answers = new List<Answer>
{
new Answer {Answer1="London", Answer2 = "Berlin", QuestionID= 1},
new Answer {Answer1="Paris", Answer2 = "Berlin", QuestionID = 2}
};
ViewBag.Answers = answers;
return View(questions);
}
}
并查看索引:
@using WebApplication2.Models;
@model List<Question>
@{
ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
@Html.Label(Model[i].name)
{
for (int j = 0; j < ViewBag.Answers.Count; j++)
{
if (Model[i].ID == ViewBag.Answers[j].QuestionID)
{
@Html.RadioButtonFor(a => Model[i].name, ViewBag.Answers[j].Answer1 as string)
@Html.RadioButtonFor(a => Model[i].name, ViewBag.Answers[j].Answer2 as string)
}
}
}
}
<input type="submit" value="ok" />
}
在这个表格之后,我在这里得到结果:
[HttpPost]
public ActionResult Index(List<Question> questions)
{
return RedirectToAction("Index");
}
如果我选择两个单选按钮,我会在(列出问题)上获得值,但是 如果我不选择第一个单选按钮,我会得到空值,即使我选择了另一个单选按钮。
我知道我是否使用简单的 html-helper,例如@Html.RadioButton("GetValue1", ViewBag.Answers[j].Answer1 as string) 并更改“发布”控制器
[HttpPost]
public ActionResult Index(string GetValue1)
{
return RedirectToAction("Index");
}
我会得到值,但我想使用 StronglyTyped Helper。那么,我如何在这个项目上使用集合。我需要发送 String.empty 而不是 null。
【问题讨论】:
-
能发一下 HTML 是如何生成的吗?
-
<form action="/" method="post"><label for="What_is_the_capital_of_Germany">What is the capital of Germany</label> <input name="[0].name" type="radio" value="London" /><input name="[0].name" type="radio" value="Berlin" /><label for="What_is_the_capital_of_France">What is the capital of France</label> <input name="[1].name" type="radio" value="Paris" /><input name="[1].name" type="radio" value="Berlin" /> <input type="submit" value="ok" /> </form>
标签: c# asp.net-mvc radio-button