简体   繁体   中英

How to add two models in one view ASP.NET MVC

I have two models. The 1st model contains every record in the database. The 2nd model contains the highest amount in the records.

How can I get two models in one view? I am new to Asp.NET MVC and just trying to get the hang of it.

Here is the code.

Model

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();


        }
    }

}

Controller

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);
        }

View

@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>

You can create a custom class with two model's properties like in this example:

public sealed class CharitiesIndexViewModel {
     public List<Charity> Charities { get; set; }
     public Highest Highest { get; set; }
}

After, in your View, you can use it:

@model CharitiesIndexViewModel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM