我有一个视图,当用户点击提交时,将有来自文本框和复选框的数据发回并保存到我的数据库中。首次加载视图时,一些文本框会从数据库中为用户加载数据,我还希望预先选中某些复选框。到目前为止,这是我在 Get 方法中得到的内容:
//vm is an object of my ViewModel
[HttpGet]
public ActionResult AddOrganization(int peopleID = 0)
{
var peopleModel = db.People.Include("EmployeeContacts").Single(g => g.PeopleID == peopleID);
var contactModel = db.EmployeeContacts.Include("People").Single(g => g.PeopleID == peopleID);
vm.People = new People();
vm.EmployeeContacts = new EmployeeContacts();
vm.OrganizationsOptions = new OrganizationOptions();
// grabs info from db to be populated in the view
vm.People.NID = peopleModel.NID;
vm.People.FirstName = peopleModel.FirstName;
vm.People.LastName = peopleModel.LastName;
vm.People.SID = peopleModel.SID;
vm.EmployeeContacts.Email = contactModel.Email;
vm.EmployeeContacts.PrimaryPhone = contactModel.PrimaryPhone;
var list = new List<AddOrganizationViewModel>
{
new AddOrganizationViewModel{ID = 1, Name = "Admin", AdminChecked = true},
new AddOrganizationViewModel{ID = 2, Name = "Breakdown Report", BreakdownReportChecked = true},
new AddOrganizationViewModel{ID = 3, Name = "Favorites", FavoritesChecked = true},
new AddOrganizationViewModel{ID = 4, Name = "Site Admin", SiteAdminChecked = false},
};
return View("../Setup/AddOrganization", vm);
}
我的 ViewModel 看起来像这样:
public class AddOrganizationViewModel
{
public Music.Models.Organizations Organizations { get; set; }
public Music.Models.People People { get; set; }
public Music.Models.OrganizationOptions OrganizationsOptions { get; set; }
public Music.Models.EmployeeContacts EmployeeContacts { get; set; }
public int ID { get; set; }
public string Name { get; set; }
public bool AdminChecked { get; set; }
public bool BreakdownReportChecked { get; set; }
public bool FavoritesChecked { get; set; }
public bool SiteAdminChecked { get; set; }
}
这是我的视图中包含复选框的部分,但我不确定我需要在这里做什么才能将我的 ViewModel、Controller 和 View 链接在一起,因为视图需要一种 AddOrganizationViewModel,我被卡住了关于如何发送复选框列表。
@model Music.ViewModels.AddOrganizationViewModel
@using (Html.BeginForm("AddOrganization", "AddOrganization")){
@Html.AntiForgeryToken()
<legend>OPTIONS</legend>
<div>
@Html.Label("Features: Admin")
@Html.CheckBoxFor(Model => Model.AdminChecked)
</div>
<div>
@Html.Label("Features: Breakdown Report")
@Html.CheckBoxFor(Model => Model.BreakdownReportChecked)
</div>
<div>
@Html.Label("Features: Favorites")
@Html.CheckBoxFor(Model => Model.FavoritesChecked)
</div>
<div>
@Html.Label("Features: Site Admin")
@Html.CheckBoxFor(Model => Model.SiteAdminChecked)
</div>
}
编辑:更新代码以反映我使用 CheckBoxFor 所做的更改。