我有两个型号。第一个模型包含数据库中的每个记录。第二个模型包含记录中的最高金额。
如何在一个视图中获得两个模型?我是Asp.NET MVC的新手,只是试图掌握它。
这是代码。
模型
namespace CharitySite.Models
{
public class Charity
{
public int ID { get; set; }
public string DisplayName { get; set; }
public DateTime Date { get; set; }
public Double Amount { get; set; }
public Double TaxBonus { get; set; }
public String Comment { get; set; }
}
public class CharityDBContext : DbContext //controls information in database
{
public Charity Highest { set; get; }
public DbSet<Charity> Donations { get; set; } //creates a donation database
public CharityDBContext()
{
this.Highest = new Charity();
}
}
}
控制器
namespace CharitySite.Controllers
{
public class CharitiesController : Controller
{
private CharityDBContext db = new CharityDBContext();
// GET: Charities
public ActionResult Index()
{
var AllDonations = new CharityDBContext();
var all = db.Donations.OrderByDescending(s => s.Amount);
if (all.Any())
{
//Get the highest amount record
var h = all.First();
AllDonations.Highest.DisplayName = h.DisplayName;
AllDonations.Highest.Amount = h.Amount;
AllDonations.Highest.Comment = h.Comment;
}
return View(AllDonations);
}
查看
@model IEnumerable<CharitySite.Models.Charity>
@model CharitySite.Models.CharityDBContext
@{
ViewBag.Title = "Index";
}
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
<div id="header">
<h1>Syria</h1>
</div>
<h2>Highest</h2>
<p>@Model.Highest.Amount</p>
<p>@Model.Highest.DisplayName</p>
<h2>Highest</h2>
<p>@Model.Highest.Amount</p>
<p>@Model.Highest.DisplayName</p>
<h2>Highest</h2>
<p>@Model.Highest.Amount</p>
<p>@Model.Highest.DisplayName</p>
<div class="table-title">
@Html.Partial("_Database", Model);
</div>
答案 0 :(得分:2)
您可以使用两个模型的属性创建自定义类,如下例所示:
public sealed class CharitiesIndexViewModel {
public List<Charity> Charities { get; set; }
public Highest Highest { get; set; }
}
之后,在您的视图中,您可以使用它:
@model CharitiesIndexViewModel