我想将视图中的值传递给MVC中的控制器。我正在使用ViewModel,通常这些值只要名称相同就会绑定到属性。但是,因为值是通过foreach循环生成的,所以这些值的名称与视图模型中的属性名称不匹配。MVC:从视图传递价值到控制器
我正在通过将值分配给Razor中的变量来解决这个问题。然而,我的一个值是在窗体上的文本框中,值并没有传递给控制器,我无法弄清楚为什么。
单击按钮时,我得到一个空例外。
VIEW代码如下:
@model PagedList.IPagedList<Mojito.Domain.ViewModels.ShoppingCartProductItem>
@using System.Web.UI.WebControls
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Mojito Products</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Description)
</th>
<th>
@Html.ActionLink("Price", "Index", new { sortOrder = ViewBag.SortByPrice, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Quantity)
</th>
<th>
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.TextBoxFor(modelItem => item.Quantity)
</td>
<td>
@{string Description = item.Description;}
@{decimal Price = item.Price;}
@{int Quantity = item.Quantity; }
@using (Html.BeginForm("AddToCart", "ShoppingCart", FormMethod.Post))
{
<div class="pull-right">
@if (Request.Url != null)
{
<input type="text" hidden="true" name="Description" [email protected] />
<input type="text" hidden="true" name="Price" [email protected] />
<input type="text" hidden="true" name="Quantity" [email protected] />
@Html.Hidden("returnUrl", Request.Url.PathAndQuery)
<input type="submit" class="btn btn-success" value="Add to cart" />
}
</div>
}
</td>
</tr>
}
</table>
<div class="col-md-12">
Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
</div>
@Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))
控制器下面
public ActionResult AddToCart(Cart cart, MojitoProduct product, string returnUrl, int Quantity =1)
{
if (product != null)
{
cart.AddItem(product, Quantity);
}
return RedirectToAction("Index", new { returnUrl });
}
我试过,但没有奏效 - 感谢思想 – ccocker 2014-09-05 17:22:49