我有一个简单的EntityFramework模型,我尝试使用复选框进行过滤。
我的模型包含2个属性:
public class Company
{
public string Name { get; set; }
public string Location { get; set; }
}
我想做的是:
我不确定如何最好地解决这个问题 - 我想我需要一个关于我的公司和位置的视图模型,但我不确定如何显示复选框列表然后按它们进行过滤。 / p>
答案 0 :(得分:3)
只需添加IsSelected
属性以及公司和位置属性即可。您的复选框应该连接到那些。然后,当用户提交表单时,您的模型将获取这些值。您可以根据IsSelected为true来过滤数据并返回匹配的行。
修改以显示示例。用IE快速测试,因为它是一个如此积极的缓存怪物:
快速说明。已经很晚了,我累了。采取这个概念,但更清楚地思考你的对象和存储。这只是一个有效的例子。
首先是ViewModel:
public class CompanyModel
{
public string Name { get; set; }
public string Location { get; set; }
public bool IsSelected { get; set; }
}
控制器中的Get和Post操作:
static IList<CompanyModel> CompanyList = null;
public ActionResult Company()
{
if (CompanyList == null)
{
CompanyList = new List<CompanyModel>()
{
new CompanyModel() { Name = "Company 1", Location = "Boston" },
new CompanyModel() { Name = "Company 2", Location = "New York" },
new CompanyModel() { Name = "Company 3", Location = "Chicago" },
new CompanyModel() { Name = "Company 4", Location = "Austin" }
};
}
return View(CompanyList);
}
[HttpPost]
public ActionResult Company(CompanyModel[] companies)
{
CompanyList = companies.Where(c => c.IsSelected).ToList();
return RedirectToAction("Company");
}
这演示了Post,Redirect,Get模式,以确保浏览器不会显示来自缓存的错误结果,并且如果用户刷新将重新提交原始表单的屏幕,则不会导致意外行为。
现在使用脚手架代码进行编辑屏幕的视图:
@model IList<MVCEditorTemplateDemo.Models.CompanyModel>
@{
ViewBag.Title = "Company";
}
<h2>Company</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CompanyModel</h4>
<hr />
@Html.ValidationSummary(true)
@for (int i = 0; i < Model.Count(); i++)
{
<div class="form-group">
@Html.LabelFor(model => model[i].Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model[i].Name)
@Html.ValidationMessageFor(model => model[i].Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].Location, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model[i].Location)
@Html.ValidationMessageFor(model => model[i].Location)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model[i].IsSelected, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model[i].IsSelected)
@Html.ValidationMessageFor(model => model[i].IsSelected)
</div>
</div>
}
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>