[英]Execute code when clicking on a html element without redirecting or reloading page
So I am working on a webshop where the user should be able to add a product to the shopping cart by clicking an icon. 所以我在网上商店工作,用户应该可以通过点击图标将产品添加到购物车。 The problem being is how would I add the selected product to the database (I am using EFCore). 问题是如何将所选产品添加到数据库(我正在使用EFCore)。 Also, as said in the title, I do no want the page to get reloaded or anything similar. 另外,正如标题中所述,我不希望页面重新加载或类似。
Calling an HttpPost request which would reload the page since I am returning the same View as I am already in. 调用一个HttpPost请求会重新加载页面,因为我正在返回与我已经存在的相同的视图。
Please find the code snippet (JS & C#) below. 请在下面找到代码段(JS和C#)。 Please modify it as per your requirement & mention in the comments box if you faced any issue.. Thanks. 如果您遇到任何问题,请根据您的要求进行修改并在评论栏中提及..谢谢。
let _data = {
id: 1,
name: 'product name',
count: 4
};
$.ajax({
type: "POST",
url: "shoppingcart/add", // "{Controller}/{ActionMethod}". If in same controller, then just use the action method name.
data: _data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response); // In real time, read response object & use as required.
},
error: function (err) {
handleError(err);
}
});
function handleError(err) {
console.log(`Sorry, an error occurred, details: ${err.error}`);
}
/* C# Controller */
[Route("api/shoppingcart")]
[ApiController]
public class ShoppingCart : ControllerBase
{
[Route("add")]
[HttpPost]
public IActionResult AddProduct(Product product)
{
return Ok(product);
}
}
/* C# model */
public class Product
{
public int id { get; set; }
public string name { get; set; }
public int count { get; set; }
}
You need to do the following: 1) Send either a GET or POST request(depending on your needs) to the relevant action/controller in your ASP.NET application by using AJAX. 您需要执行以下操作:1)使用AJAX向ASP.NET应用程序中的相关操作/控制器发送GET或POST请求(具体取决于您的需要)。 2) Make sure the action method returns whatever you need to change on the page - most of the times I either return a partial view or a json. 2)确保action方法返回你需要在页面上更改的内容 - 大多数时候我要么返回局部视图,要么返回json。 3) In the callback of the AJAX request that you sent, use the json/partial view(html) that was returned to you in the response by your action method to alter the DOM of the page as you need. 3)在您发送的AJAX请求的回调中,使用您的操作方法在响应中返回给您的json / partial视图(html)来根据需要更改页面的DOM。 Note: The reason you are returning a partial view and not a regular view is to omit the _layout in the HTML that you receive. 注意:返回部分视图而不是常规视图的原因是省略您收到的HTML中的_layout。
I might need more information to be able to help. 我可能需要更多信息才能提供帮助。 If you are using ef migrations and have a Model already, called Product for example, but note a database, do the following steps: 如果您正在使用ef迁移并且已经具有Model(例如Product),但请注意数据库,请执行以下步骤:
dotnet ef migrations add InitialCreated --output-dir Migrations --context YourDbContext dotnet ef database update --context YourDbContext
dotnet tool install dotnet-aspnet-codegenerator
使用此命令安装它: dotnet tool install dotnet-aspnet-codegenerator
Now make sure the following lines are added to your csproj file. 现在确保将以下行添加到csproj文件中。
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
dotnet aspnet-codegenerator controller -name ProductsController -m Product -dc YourDbContext --relativeFolderPath Controllers --useDefaultLayout --referenceScriptLibraries
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
<a asp-action="Create" asp-controller="Products" method="post" >Create New</a>
Note! 注意! Products does not have the workd Controller after it. 产品之后没有工作控制器。
Below is an example of the Create.cshtml web page 下面是Create.cshtml网页的示例
@model test_mvc_webapp.Models.Product
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Product</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-controller="Products" asp-action="Create" method="post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ProductCode" class="control-label"></label>
<input asp-for="ProductCode" class="form-control" />
<span asp-validation-for="ProductCode" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="ProductType" class="control-label"></label>
<input asp-for="ProductType" class="form-control" />
<span asp-validation-for="ProductType" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Description" class="control-label"></label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Let me know if this helped? 如果这有帮助,请告诉我?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.