简体   繁体   English

在 asp.net 核心 2.2 中显示 url slug 而不是 id

[英]display url slug instead of id in asp.net core 2.2

actually I can not want to visible my id when I was something delete.so I want to slug here.but can not understand how I modify or convert id to slug type.实际上,当我删除某些东西时,我不想看到我的 id。所以我想在这里 slug。但无法理解我如何修改或将 id 转换为 slug 类型。 here is my code:这是我的代码:

startup.cs启动.cs


            app.UseMvc(routes =>
            {
                routes.MapRoute(
                  name: "areas",
                  template: "{area=Customer}/{controller=Home}/{action=Index}/{id?}"
                );
            });
    [HttpGet]
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                NotFound();
            }

            var product = _db.Spray.Include(c => c.ProductTypes).FirstOrDefault(c => c.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return View(product);
        }



        [HttpPost]
        [ActionName("Delete")]      //DeleteConfirm nam ke delete namei chinbo




        public async Task<IActionResult> DeleteConfirm(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }
            var product = _db.Spray.FirstOrDefault(c => c.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            _db.Spray.Remove(product);
            await _db.SaveChangesAsync();

            return RedirectToAction(nameof(Index));
        }
    }
}

Delete.cshtml删除.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>


I have no idea to add how to add slug.我不知道如何添加 slug。 I don't want to see my visible id for that I tried to make its slug.我不想看到我的可见身份,因为我试图制造它的蛞蝓。 but I don't understand actually how to take process.但我实际上不明白如何处理。 I am beginner, please help anyone.我是初学者,请帮助任何人。

It seems you want to make id unvisible in the url, the simple way is to change Delete action to the post type.似乎您想让 id 在 url 中不可见,简单的方法是将删除操作更改为帖子类型。

Index.cshtml:索引.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>

Controller: Controller:

[HttpPost]
public ActionResult Delete(int? id)
{
     //..
}

[HttpPost]
//[ActionName("Delete")]    
public async Task<IActionResult> DeleteConfirm(int? id)
{
    //...
}

Be sure your Delete.cshtml should be like below:确保您的 Delete.cshtml 应如下所示:

<form asp-action="DeleteConfirm" method="post" enctype="multipart/form-data">

Result:结果: 在此处输入图像描述

Update:更新:

Index.cshtml:索引.cshtml:

<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>

Controller: Controller:

[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)
{
    //...
}

Startup.cs:启动.cs:

app.UseEndpoints(endpoints =>
{               
      endpoints.MapControllerRoute(
             name: "default",
             pattern: "{controller=Home}/{action=Index}/{slug?}");
});

Result:结果: 在此处输入图像描述

Whole Controller:整个 Controller:

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);
    }
}

Whole Startup.cs:整个 Startup.cs:

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?}");
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM