我有一个李克特调查生成器,可以输入动态数量的问题 - 然后用户浏览并使用 4 个单选按钮回答每个问题(强烈不同意、不同意、同意、强烈同意)。
我可以很容易地输出它们 - 但它们可以在回发时进行模型绑定吗?还是我必须遍历发布的表单元素(即不使用模型绑定)?
可以吗?
如果你想在视图中绑定一个列表,这里有一个关于将列表与输入名称绑定的演示:
型号:
public class Qusetion
{
public string Content { get; set; }
public string Answer { get; set; }
}
查看:
<form method="post">
<div>
<label>question1</label>
<input name="list[0].Content" value="question1" hidden/>
<div>
<input type="radio" name="list[0].Answer" value="Strongly Disagree" />Strongly Disagree
<input type="radio" name="list[0].Answer" value="Disagree" />Disagree
<input type="radio" name="list[0].Answer" value="Agree" />Agree
<input type="radio" name="list[0].Answer" value="Strongly Agree" />Strongly Agree
</div>
</div>
<div>
<label>question2</label>
<input name="list[1].Content" value="question2" hidden/>
<div>
<input type="radio" name="list[1].Answer" value="Strongly Disagree" />Strongly Disagree
<input type="radio" name="list[1].Answer" value="Disagree" />Disagree
<input type="radio" name="list[1].Answer" value="Agree" />Agree
<input type="radio" name="list[1].Answer" value="Strongly Agree" />Strongly Agree
</div>
</div>
<div>
<label>question3</label>
<input name="list[2].Content" value="question3" hidden/>
<div>
<input type="radio" name="list[2].Answer" value="Strongly Disagree" />Strongly Disagree
<input type="radio" name="list[2].Answer" value="Disagree" />Disagree
<input type="radio" name="list[2].Answer" value="Agree" />Agree
<input type="radio" name="list[2].Answer" value="Strongly Agree" />Strongly Agree
</div>
</div>
<input type="submit" value="submit" />
</form>
控制器:
public IActionResult BindList(List<Qusetion> list)
{
return View();
}
更新:
如果你想用循环绑定。你可以将列表传递给视图。代码会起作用是因为.net core绑定模型具有名称属性。并且因为你想绑定列表,所以名称会像
list[index].xxx
。
这是一个带循环的演示:
查看:
@model IEnumerable<Qusetion>
<form method="post">
@{ var i = 0;}
@foreach (var question in Model)
{
<div>
<label>@question.Content</label>
<input name="list[@i].Content" value="@question.Content" hidden />
<div>
<input type="radio" name="list[@i].Answer" value="Strongly Disagree" />Strongly Disagree
<input type="radio" name="list[@i].Answer" value="Disagree" />Disagree
<input type="radio" name="list[@i].Answer" value="Agree" />Agree
<input type="radio" name="list[@i].Answer" value="Strongly Agree" />Strongly Agree
</div>
</div>
i++;
}
<input type="submit" value="submit" />
</form>
控制器:
public IActionResult BindList(List<Qusetion> list)
{
List<Qusetion> list1 = new List<Qusetion> { new Qusetion { Content = "question1" }, new Qusetion { Content = "question2" }, new Qusetion { Content = "question3" } };
return View(list1);
}