INSERT INTO SaleItem (ProdId, SaleQuantity) SELECT ProdId, BasketProdQuantity FROM Basket;
这是我的SQL命令,我希望将它与视图上的按钮一起使用。但我不知道如何用视图上的按钮引用方法。我应该使用SqlConnection connection = new SqlConnection(connectionString)
我已经将我的数据库与WebConfig连接,并将其作为DefaultConnection连接。
编辑: 我是MVC和Web编码的新手,所以我不知道该怎么做。
[HttpPost]
public ActionResult Buy(SaleItem saleitem)
{
if (ModelState.IsValid)
{
string query = "INSERT INTO SaleItem (ProdId, SaleQuantity) SELECT ProdId, BasketProdQuantity FROM Basket";
db.Database.ExecuteSqlCommand(query);
db.SaveChanges();
return RedirectToAction("Index", "Basket");
}
return View(saleitem);
}
并且有观点认为我想使用购买方法。
@model IEnumerable<VeriPark001.Models.Basket>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Product.Book.BookName)
</th>
<th>
@Html.DisplayNameFor(model => model.BasketProdQuantity)
</th>
<th>
@Html.DisplayNameFor(model => model.Product.ProdPrice)
</th>
<th>
Total
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Product.Book.BookName)
@Html.DisplayFor(modelItem => item.Product.MovieDVD.DVDName)
@Html.DisplayFor(modelItem => item.Product.MusicCD.CDName)
</td>
<td>
@Html.DisplayFor(modelItem => item.BasketProdQuantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.Product.ProdPrice)
</td>
<td>
@(item.Product.ProdPrice * item.BasketProdQuantity)
</td>
<td>
<button>@Html.ActionLink("Delete", "Delete", new { id = item.BasketId })</button>
<button>@Html.ActionLink("Update quantity", "Edit", new { id = item.BasketId })</button>
</td>
</tr>
}
</table>
<p>
<button>I WANT TO CALL ACTION HERE. I search for how to do that and couldn't find a proper way.</button>
<button>@Html.ActionLink("Products", "Index", "Product")</button>
</p>
答案 0 :(得分:0)
您可以使用Html.BeginForm并向控制器操作发送帖子请求。
替换
<p>
<button>I WANT TO CALL ACTION HERE. I search for how to do that and couldn't find a proper way.</button>
<button>@Html.ActionLink("Products", "Index", "Product")</button>
</p>
与
@using (Html.BeginForm("Buy", "YourController", FormMethod.Post))
{
// Input for your SaleItem model
<button class="btn btn-group btn-group-sm" type="submit">Submit</button>
}
由于您的“购买”操作需要SaleItem模型,因此我会将其留给您。