c# - 使用其 ID 为每个产品创建一个页面
问题描述
我的问题是,我想要最简单的方法来为每个产品创建一个页面,并使用他之前存储到数据库的 ID
例子 :
首页/产品/“数据库中的产品ID”
此链接必须显示产品的“详细信息”^
目的是当我添加新产品时,会使用产品 ID 自动创建一个新页面。
控制器中的操作代码:
[HttpPost]
public ActionResult AddArticle(NewsData art)
{
var ArticleID = art.ArticleID;
using (MatrodyEntities db = new MatrodyEntities())
{
db.NewsData.Add(art);
db.SaveChanges();
}
return View(art);
}
路由配置:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
解决方案
好的,因此为了基于参数为 CRUD 操作创建链接,您可以使用 AJAX 使用参数发布数据,也可以使用Html.ActionLink
不发布但创建锚标记的方法。
1) 使用带有参数的 ActionLink:
@foreach (var item in Model)
{
<tr>
//Additional data
<td>
@Html.ActionLink("Delete", "Home", new { id = item.id})
</td>
</tr>
}
在您的Home
控制器中:
public ActionResult Delete(int id) {//Your logic}
请注意,如果您使用默认值RouteConfig
,请确保您id
作为参数发送,或者您可以根据需要创建自己的路由。
2)您还可以使用 AJAX 发布到您的控制器。你可以这样做:
@foreach (var item in Model)
{
<tr>
//Additional data
<td>
<a href="#" data-id="@item.id" onclick="confirmDelete(this)"></a>
</td>
</tr>
}
在你的 AJAX 中:
function confirmDelete(event) {
var recordToDelete = $(event).attr("data-id"); //Get our current file id here
if (confirm("Are you sure you want to delete this record") == true) {
//Prepare our data
var json = {
id: recordToDelete
};
$.ajax({
url: '@Url.Action("DeleteFile", "Home")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json) },
success: function (data) {
if(data == "success") {
alert("Successfully deleted selected file");
location.reload();
}
},
error: function (data) {
alert("Could not delete selected file. Please try again!");
},
});
}
};
最后在你的控制器中:
//Delete a file based on the ID that you get from your View
[HttpPost]
public JsonResult DeleteFile(string json)
{
var serializer = new JavaScriptSerializer();
try
{
dynamic jsondata = serializer.Deserialize(json, typeof(object));
string id = jsondata["id"];
if(id != "")
{
int getid = Convert.ToInt32(id);
//Call your db or your logic to delete the file
DatabaseAccess data = new DatabaseAccess();
string result = data.DeleteFile(getid);
if(result.Equals("Success"))
{
return Json("success", JsonRequestBehavior.AllowGet);
}
else
{
return Json("fail", JsonRequestBehavior.AllowGet);
}
}
else
{
return Json("notfound", JsonRequestBehavior.AllowGet);
}
}
catch
{
return Json("dberror", JsonRequestBehavior.AllowGet);
}
}
推荐阅读
- javascript - Rails 6,覆盖@rails/ujs 确认显示模式
- c# - 尝试在 asp.net 核心中首次使用 Auth0 注册后将用户数据保存到 dbcontext
- javascript - 使用javascript在二维数组中生成随机路径
- python - Python:通过定义与大型数据集匹配的列值来实现多线\任何形式的图形
- c++ - 如何防止 std::is_constructible 中的隐式转换
- c# - WIX 安装程序工具集 - SQL Server 和 IIS 快速安装
- python - Django:在 Mixins 类视图中验证受限外键表单
- r - Hadley Wickham 的书 ggplot2 Elegant Graphics for Data Analysis 中的血压案例研究问题
- javascript - Array.push 没有正确添加项目
- android - 数字角色 SDK - 原生问题