我有一个我需要更新的MVC视图。当前代码如下所示:
查看 -
@{
ViewBag.Title = "TestView";
}
<div class="row">
<div class="col-lg-12">
<h4>Current Report 1</h4>
@if (@ViewBag.DocID != null)
{
<p><a href="javascript:void(0);" onclick="DownloadFile('@ViewBag.DocID');" title="@ViewBag.DocName">@ViewBag.DocName</a> - <small>@ViewBag.UploadDateTime</small></p>
}
else
{
<p>There is not a current Report in the system at this time.</p>
}
</div>
</div>
控制器 -
public ActionResult TestView()
{
Report report = new Report();
SearchCriteria sc = new SearchCriteria();
sc.User = SessionData.User;
sc.DocType = 1;
report = DAL.GetReportWithTypeAndUser(sc);
if(report != null)
{
ViewBag.DocID = report.DocID;
ViewBag.DocName = report.DocName;
ViewBag.UploadDateTime = report.UploadDateTime;
}
return View();
}
这段代码很有用。但我需要重复几种报告类型。在我的控制器中,我目前发送一个DocType = 1,但我需要发送2,3,4等等,然后返回几种不同类型,并按照我目前在视图中的方式列出它们。
我很难找到最好的方法来做到这一点。任何帮助将不胜感激!
答案 0 :(得分:1)
不要使用ViewBag
。改为使用ViewModels。
视图模型:
public class ReportsViewModel
{
public ICollection<Report> Reports;
}
实体:
public class Report
{
public int DocID { get; set; }
public string DocName { get; set; }
public DateTime UploadDateTime { get; set; }
}
控制器:
public ActionResult TestView()
{
// get your reports with different types
var reports = GetYourReports();
var vm = new ReportsViewModel
{
Reports = reports
}
return View(vm);
}
查看:
@model ReportsViewModel
@{
ViewBag.Title = "TestView";
}
<div class="row">
<div class="col-lg-12">
@if (Model.Reports.Length > 0)
{
@foreach (var report in Models.Reports)
{
<p><a href="javascript:void(0); "onclick="DownloadFile('@report.DocID');" title="@report.DocName">@report.DocName</a> - <small>@report.UploadDateTime</small></p>
}
}
else
{
<p>There is not a current Report in the system at this time.</p>
}
</div>
</div>
答案 1 :(得分:0)
为什么不创建视图模型并将视图绑定到该模型?
public class Report
{
public int DocType {get; set;}
public int DocId {get; set;}
public string DocName {get; set;}
// Other properties
}
然后,您可以通过在视图顶部添加@model Report
将视图绑定到此模型,并通过在视图中执行@Model.DocType
等来访问属性。您甚至可以在视图中编写更复杂的逻辑,并根据DocType
自定义它。
在控制器中,您可以创建Report
类的实例,并为其属性指定适当的值,并在实例化时将此对象传递给View
。