如何在MVC中将值从一个视图传递到另一个视图?

时间:2016-03-07 20:56:04

标签: c# asp.net-mvc asp.net-mvc-4

我想从索引中显示总金额(@totalAmount),并将其显示在下一页的付款页面上。我试图使用一个viewbag,但它似乎没有用。

这是我的索引...

@model IEnumerable<charity.Models.Donation>

@{
ViewBag.Title = "Index";
ViewBag.total = "@totalAmount";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.DisplayName)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Date)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Amount)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.TaxBonus)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Comment)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
            @Html.DisplayFor(modelItem => item.DisplayName)
        </td>
    <td>
        @Html.DisplayFor(modelItem => item.Date)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Amount)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.TaxBonus)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Comment)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
        @Html.ActionLink("Details", "Details", new { id=item.ID }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.ID })
    </td>
</tr>
}

</table>
@{

   Decimal totalAmount = 0;
if (Model != null)
{
    totalAmount = Model.Sum(x => x.Amount);
}
<label>Total amount donated</label>
<h1 id="amount">@totalAmount</h1>
}

@{

Decimal totaltax = 0;
if (Model != null)
{
    totaltax = Model.Sum(x => x.TaxBonus);
}
<label>Total tax bonus</label>
<h1 name="amount">@totaltax</h1>
}

这是我的付款页面......

@{
ViewBag.Title = "Payment";
}

<h2>Payment</h2>
<form>
<h1>@ViewBag.total</h1>
</form>

来自控制器的索引和付款代码......

 public ActionResult Index()
    {

        return View(db.Donations.ToList());


    }
   public ActionResult Payment() {

        return View();

    }

1 个答案:

答案 0 :(得分:1)

尝试使用会话变量而不是ViewBag。 它会将总数存储为int。

    Session["totalAmount"] = Model.Sum(x => x.Amount);