【发布时间】:2015-10-31 20:10:25
【问题描述】:
假设我有一堂课
public class Person
{
public int id { get; set; }
public string name { get; set; }
public List<int> list_of_friends { get; set; }
}
朋友列表包含所选人员的朋友的 ID。 我在创建表单以创建新人时遇到问题。它应该有 id 和 name 两个字段,然后是所有人的清单,以检查新人是否与他们中的任何人成为朋友。到目前为止,我得到了这个:
我的控制器:
// GET: Person/Create
public ActionResult Create()
{
var model = new Person();
return View(model);
}
// POST: Person/Create
[HttpPost]
public ActionResult Create(Person person)
{
person.id = new Random().Next();
try
{
var list = (List<Person>)Session["list_of_people"];
if (list != null)
{
list.Add(person);
}
else
{
list = new List<Person>();
list.Add(person);
}
Session["list_of_people"] = list;
return RedirectToAction("List");
}
catch
{
return View();
}
}
(我应该使用 Session 对象 - 不要感到惊讶) 我的观点似乎是问题所在:
<div class="form-horizontal">
<h4>Person</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@if (Session["list_of_people"] != null)
{
List<Person> list = (List<Person>)Session["list_of_people"];
<p class="lista">List of friends</p>
@for (int i = 0; i < list.Count; i++)
{
@Html.CheckBoxFor(m => ??)
@Html.HiddenFor(m => ??)
@Html.LabelFor(m => ??)
<br />
}
}
</div>
我不知道如何填写 ?? 的。有人可以帮忙吗?
【问题讨论】:
-
尽量不要使用会话。出于多种原因,这是一种不好的做法,而且无论如何都对这些东西过度杀伤。在生成 CheckBoxFor/hiddenfor/labelfor 时需要使用索引器,否则它将无法正确回发列表。 stackoverflow.com/questions/20687121/…
-
@Ahmedilyas,使用 Session 是不好的做法的原因是什么?
-
您需要一个视图模型来代表您想要显示/编辑的内容。在您的情况下,
PersonVM包含属性List<FriendVM> Friends,其中FriendVM包含属性int ID、string Name和bool IsSelected。示例参考this answer
标签: c# asp.net-mvc