我们说我有一个班级
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>
我不知道如何填写“??”。有人可以帮忙吗?
答案 0 :(得分:0)
试试这个兄弟,希望它有所帮助;
@for (var i =0; i< Person.list_of_friends.Count(); i++){
@Html.HiddenFor(model => model.list_of_friends[i])
@Html.CheckBoxFor(model => model.list_of_friends[i].Selected)
@Html.LabelFor(model=> model.list_of_friends[i].name)
}
如果我做对了它应该有效;
试着看看这个教程也可能对你有帮助:
Updating Related Data with the Entity Framework in an ASP.NET MVC Application (6 of 10)