我有一个执行以下操作的控制器操作:
然而,MVC不断抛出错误"序列不包含匹配元素"我正在努力弄清楚原因。
帐户控制器,它会获取产品列表并将其添加到用户的帐户中
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> AddProduct(List<Product> products)
{
//var acc = FetchCurrentUserAccount();
if (db.Accounts != null)
{
var acc = db.Accounts.Find(UserManager.FindByIdAsync(User.Identity.GetUserId()).Result.Account.AccountID);
foreach (var product in products)
{
if (product.IsSelected)
{
product.PaymentStatus = enPaymentStatus.Pending
acc.ProductsPurchased.Add(product);
}
}
await db.SaveChangesAsync();
return RedirectToAction("Pay", "Products", new {id = acc.AccountID} );
}
return HttpNotFound();
}
采用AccountID的产品控制器,查找帐户并将其作为模型传递给View:
[HttpGet]
public ActionResult Pay(int? id)
{
var acc = db.Accounts.Find(id);
return View(acc);
}
视图本身:
@using PPPv2.Models
@model Account
@{ var subtotal = 0.0d;}
<h2>Payment:</h2>
@if (Model != null)
{
<h4>Thank you @Model.Salutation @Model.LastName</h4>
<h4>Please check that the product(s) and amounts below are correct before completing your purchase.</h4>
foreach (var item in Model.ProductsPurchased)
{
<div>
@Html.DisplayFor(modelItem => item.Name)
<div>
@Html.DisplayFor(modelItem => item.Price)
@{ subtotal += item.Price; }
</div>
</div>
}
<div>
Total to pay:
<div>
@Html.Display(String.Format("£{0:#,###0.00}", subtotal))
</div>
</div>
@Html.ActionLink("Pay", "Process", "Products", new {id = Model.ProductsPurchased.First(x => x.PaymentStatus == enPaymentStatus.Sold)}, new {@class = "btn btn-warning"})
}
else
{
<div>
No products were found in your cart... Odd...
<div>
@Html.ActionLink("Select a product", "AddProduct", "Account", null, new {@class = "btn btn-warning"})
</div>
</div>
}
注意事项:
有什么想法吗?
答案 0 :(得分:2)
在这一行:
@Html.ActionLink("Pay", "Process", "Products",
new {id = Model.ProductsPurchased.First(x => x.PaymentStatus == enPaymentStatus.Sold)},
new {@class = "btn btn-warning"})
您需要先添加一个条件,检查ProductsPurchased集合中是否有任何状态为已售出的商品。您可能还希望确保显示状态为已售出的产品,或者更确切地说,如您的控制器代码所示,状态为待处理的产品。
所以,基本上
if(Model.ProductsPurchased.Any(x => x.PaymentStatus == enPaymentStatus.Sold/*or Pending?*/)){
@Html.ActionLink("Pay", "Process", "Products",
new {id = Model.ProductsPurchased.First(x => x.PaymentStatus == enPaymentStatus.Sold/*or Pending?*/)},
new {@class = "btn btn-warning"})
}
答案 1 :(得分:0)
我不确定是什么修复,但我相信你并不是在等待acc返回,更准确地说是返回。
UserManager.FindByIdAsync(User.Identity.GetUserId()).Result.Account.AccountID
因为您正在使用异步,所以我希望您在尝试使用结果之前使用await。 你试过mak
吗?