C# 在asp.net core 2.2中显示url slug而不是id
事实上,当我被删除时,我不想看到我的id。所以我想在这里使用slug。但我不明白如何修改id或将id转换为slug类型。 这是我的密码: startup.csC# 在asp.net core 2.2中显示url slug而不是id,c#,asp.net-core,asp.net-core-mvc,C#,Asp.net Core,Asp.net Core Mvc,事实上,当我被删除时,我不想看到我的id。所以我想在这里使用slug。但我不明白如何修改id或将id转换为slug类型。 这是我的密码: startup.cs app.UseMvc(routes => { routes.MapRoute( name: "areas", template: "{area=Cus
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area=Customer}/{controller=Home}/{action=Index}/{id?}"
);
});
[HttpGet]
公共操作结果删除(int?id)
{
if(id==null)
{
NotFound();
}
var product=_db.Spray.Include(c=>c.ProductTypes).FirstOrDefault(c=>c.Id==Id);
如果(产品==null)
{
返回NotFound();
}
返回视图(产品);
}
[HttpPost]
[ActionName(“删除”)]//删除确认nam ke删除名称i chinbo
公共异步任务DeleteConfirm(int?id)
{
if(id==null)
{
返回NotFound();
}
var乘积=_db.Spray.FirstOrDefault(c=>c.Id==Id);
如果(产品==null)
{
返回NotFound();
}
_db.喷洒.去除(产品);
等待_db.SaveChangesAsync();
返回重定向到操作(名称(索引));
}
}
}
Delete.cshtml
form asp-action="Delete" method="post" enctype="multipart/form-data">
<div class="p-4 rounded border-row">
<div asp-validation-summary="ModelOnly" class="text-danger">
</div>
<div>
<div class="col-8">
<div class="form-group row">
<div class="col-4">
<label asp-for="Name"></label>
</div>
<div class="col-8">
<input type="hidden" asp-for="Id" />
<input asp-for="Name" readonly="readonly" class="form-control" />
</div>
<span asp-validation-for="Name" class="text-danger"></span>
</div>
formasp action=“Delete”method=“post”enctype=“多部分/表单数据”>
我不知道如何添加slug。我不想看到我的可见id,因为我试图使它的鼻涕虫。但我不知道该怎么做。我是初学者,请帮助任何人。似乎你想让id在url中不可见,简单的方法是将删除操作更改为帖子类型 Index.cshtml:
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
<form method="post" asp-action="Delete" asp-controller="Sprays">
<input type="hidden" value="@item.Id" name="id" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
}
</tbody>
</table>
<form method="post" asp-action="Delete" asp-controller="Sprays" asp-route-slug="my-delete-id">
<input type="hidden" value="@item.Id" name="id" />
<input type="submit" value="Delete" />
</form>
结果:
整个控制器:
[HttpPost]
public ActionResult Delete(int? id)
{
//..
}
[HttpPost]
//[ActionName("Delete")]
public async Task<IActionResult> DeleteConfirm(int? id)
{
//...
}
[HttpPost]
public async Task<IActionResult> Delete(string slug)
{
var data = HttpContext.Request.Form["id"].First();
var id = int.Parse(data);
//...
}
[HttpPost]
//[ActionName("Delete")]
public async Task<IActionResult> DeleteConfirm(int? id)
{
//...
}
public class TestsController : Controller
{
private readonly MyDbContext _context;
public TestsController(MyDbContext context)
{
_context = context;
}
// GET: Tests
public async Task<IActionResult> Index()
{
return View(await _context.Test.ToListAsync());
}
// GET: Tests/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var test = await _context.Test
.FirstOrDefaultAsync(m => m.Id == id);
if (test == null)
{
return NotFound();
}
return View(test);
}
// GET: Tests/Create
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name")] Test test)
{
if (ModelState.IsValid)
{
_context.Add(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(test);
}
// GET: Tests/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var test = await _context.Test.FindAsync(id);
if (test == null)
{
return NotFound();
}
return View(test);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] Test test)
{
if (id != test.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(test);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TestExists(test.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(test);
}
[HttpPost]
public async Task<IActionResult> Delete(string slug)
{
var data = HttpContext.Request.Form["id"].First();
var id = int.Parse(data);
var test = await _context.Test
.FirstOrDefaultAsync(m => m.Id == id);
if (test == null)
{
return NotFound();
}
return View(test);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var test = await _context.Test.FindAsync(id);
_context.Test.Remove(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool TestExists(int id)
{
return _context.Test.Any(e => e.Id == id);
}
}
公共类TestsController:控制器
{
私有只读MyDbContext\u context;
公共TestsController(MyDbContext上下文)
{
_上下文=上下文;
}
//获取:测试
公共异步任务索引()
{
返回视图(wait_context.Test.ToListAsync());
}
//获取:测试/详细信息/5
公共异步任务详细信息(int?id)
{
if(id==null)
{
返回NotFound();
}
var test=await\u context.test
.FirstOrDefaultAsync(m=>m.Id==Id);
if(test==null)
{
返回NotFound();
}
返回视图(测试);
}
//获取:测试/创建
public IActionResult Create()
{
返回视图();
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务创建([Bind(“Id,Name”)]Test)
{
if(ModelState.IsValid)
{
_添加(测试);
wait_context.SaveChangesAsync();
返回重定向到操作(名称(索引));
}
返回视图(测试);
}
//获取:测试/编辑/5
公共异步任务编辑(int?id)
{
if(id==null)
{
返回NotFound();
}
var test=wait_context.test.FindAsync(id);
if(test==null)
{
返回NotFound();
}
返回视图(测试);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务编辑(int-id、[Bind(“id,Name”)]Test)
{
if(id!=test.id)
{
返回NotFound();
}
if(ModelState.IsValid)
{
尝试
{
_上下文更新(测试);
wait_context.SaveChangesAsync();
}
catch(DbUpdateConcurrencyException)
{
如果(!TestExists(test.Id))
{
返回NotFound();
}
其他的
{
投掷;
}
}
返回重定向到操作(名称(索引));
}
返回视图(测试);
}
[HttpPost]
公共异步任务删除(字符串段塞)
{
var data=HttpContext.Request.Form[“id”].First();
var id=int.Parse(数据);
var test=await\u context.test
.FirstOrDefaultAsync(m=>m.Id==Id);
if(test==null)
{
返回NotFound();
}
返回视图(测试);
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务删除已确认(int-id)
{
var test=wait_context.test.FindAsync(id);
_context.Test.Remove(测试);
wait_context.SaveChangesAsync();
返回重定向到操作(名称(索引));
}
私有bool TestExists(int-id)
{
返回_context.Test.Any(e=>e.Id==Id);
}
}
整个Startup.cs:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{slug?}");
});
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{slug?}");
});
}
public void配置服务(IServiceCollection服务)
{
services.AddControllersWithViews();
services.AddDbContext(options=>options.UseSqlServer(Configuration.GetConnectionString(“MyDbContext”));
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller=Home}/{action=Index}/{slug?}”);
});
}
@Rana我希望我的URL中有slug而不是post-Id。但是你让这个Id完全不可见。你想要哪种slug
public class TestsController : Controller
{
private readonly MyDbContext _context;
public TestsController(MyDbContext context)
{
_context = context;
}
// GET: Tests
public async Task<IActionResult> Index()
{
return View(await _context.Test.ToListAsync());
}
// GET: Tests/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var test = await _context.Test
.FirstOrDefaultAsync(m => m.Id == id);
if (test == null)
{
return NotFound();
}
return View(test);
}
// GET: Tests/Create
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name")] Test test)
{
if (ModelState.IsValid)
{
_context.Add(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(test);
}
// GET: Tests/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var test = await _context.Test.FindAsync(id);
if (test == null)
{
return NotFound();
}
return View(test);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name")] Test test)
{
if (id != test.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(test);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!TestExists(test.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(test);
}
[HttpPost]
public async Task<IActionResult> Delete(string slug)
{
var data = HttpContext.Request.Form["id"].First();
var id = int.Parse(data);
var test = await _context.Test
.FirstOrDefaultAsync(m => m.Id == id);
if (test == null)
{
return NotFound();
}
return View(test);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var test = await _context.Test.FindAsync(id);
_context.Test.Remove(test);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool TestExists(int id)
{
return _context.Test.Any(e => e.Id == id);
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MyDbContext")));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{slug?}");
});
}