选择选项 1:我看不出有任何理由在这种情况下使用 ViewBag。只需将模型传递给控制器操作方法中的视图即可。
return View(model);
您将有两个操作方法,都返回相同的视图。首次访问页面时的一种方法:
[HttpGet]
public ActionResult Query()
{
return View(new FormQueryModel())
}
...另一个用于用户提交搜索条件时。这将运行查询并传递一个填充了结果的模型,以便视图显示它们。
[HttpPost]
public ActionResult Query(FormQueryModel model)
{
var queryManager = new QueryManager(model);
model.QueryResults = queryManager.GetResults();
return View(model);
}
不,您不必再次将先前搜索的结果发回控制器。就我而言,我只是将结果留在表单标签之外,因此不会发回。但是只要不绑定结果就没事。
@model FormQueryModel
@using (Html.BeginForm("Query", "Home"))
{
@Html.LabelFor(m => m.Age)
@Html.TextBoxFor(m => m.Age)
@Html.LabelFor(m => m.Country)
@Html.TextBoxFor(m => m.Country)
}
@if (Model.QueryResults.Count > 0)
{
@foreach (var result in Model.QueryResults)
{
//display results here
}
}
您还需要添加一些分页,因为用户不会阅读 1000 行。如果搜索返回的行太多,用户将添加更多过滤条件。
public class FormQueryModel
{
public int PageSize { get; set; }
[Display(Name = "Enter your age")]
public int Age { get; set; }
[Display(Name = "Enter your country")]
public string Country { get; set; }
public List<QueryResult> QueryResults { get; set; }
public FormQueryModel()
{
this.QueryResults = new List<QueryResult>();
}
}