我的问题是,我想以最简单的方式为每个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);
}
RouteConfig:
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 }
);
}
}
答案 0 :(得分:0)
好的,因此,为了基于参数建立CRUD操作的链接,您可以使用AJAX通过参数来发布数据,也可以使用Html.ActionLink
而不是POST而是创建一个锚标签。
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 POST到Controller。您可以执行以下操作:
@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);
}
}