C# 在不重定向或重新加载页面的情况下单击html元素时执行代码
因此,我正在一个网上商店工作,在那里,用户应该能够通过单击图标将产品添加到购物车中。问题是如何将所选产品添加到数据库中(我使用的是EFCore)。此外,正如标题中所说,我不希望页面被重新加载或任何类似的内容 到目前为止,我尝试的是:C# 在不重定向或重新加载页面的情况下单击html元素时执行代码,c#,asp.net-core-mvc,C#,Asp.net Core Mvc,因此,我正在一个网上商店工作,在那里,用户应该能够通过单击图标将产品添加到购物车中。问题是如何将所选产品添加到数据库中(我使用的是EFCore)。此外,正如标题中所说,我不希望页面被重新加载或任何类似的内容 到目前为止,我尝试的是: 调用将重新加载页面的HttpPost请求,因为我返回的视图与我已经在的视图相同。您需要执行以下操作: 1) 使用AJAX向ASP.NET应用程序中的相关操作/控制器发送GET或POST请求(取决于您的需要)。 2) 确保action方法返回您需要在页面上更改的内容—
调用将重新加载页面的HttpPost请求,因为我返回的视图与我已经在的视图相同。您需要执行以下操作: 1) 使用AJAX向ASP.NET应用程序中的相关操作/控制器发送GET或POST请求(取决于您的需要)。 2) 确保action方法返回您需要在页面上更改的内容—大多数情况下,我要么返回部分视图,要么返回json。 3) 在您发送的AJAX请求的回调中,使用action方法在响应中返回给您的json/部分视图(html),根据需要更改页面的DOM。
注意:返回部分视图而不是常规视图的原因是忽略了收到的HTML中的_布局。请查找下面的代码片段(JS&C)。请根据您的要求进行修改,如果您遇到任何问题,请在评论框中提及。。谢谢
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; }
}
我可能需要更多的信息来提供帮助。如果您正在使用ef迁移,并且已经有了一个模型(例如称为Product),但请注意数据库,请执行以下步骤:
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务创建(
创建新的
注意!产品后面没有workd控制器
下面是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");}
}
@model test\u mvc\u webapp.Models.Product
@{
ViewData[“标题”]=“创建”;
}
创造
产品
返回列表
@节脚本{
@{wait Html.RenderPartialAsync(“_validationScript”);}
}
让我知道这是否有帮助?如果你不想重新加载它,我会说你需要使用JS。@FedericoNavarrete那么你的意思是我应该用JS在后台调用HttpPost请求?是的,我会说这是你需要做的。就我个人而言,我与ASP.NET和MVC合作过,在这两种情况下,如果你需要保留同一页面,你需要使用jQuery、pure或其他框架的JS。您可以使用AJAX将数据异步发布到服务器。为此,您需要在后端(asp.Net core)创建一个API端点。请共享您使用的客户端技术,即纯JavaScript或jQuery或AngularJS或AngularJSetc@PrateekKumarDalbehera我主要使用JQuery
<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>
@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");}
}