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

肖恩·沃森

实际上,当我被删除时,我不希望看到我的ID。所以我想在这里一下,但是不明白如何修改ID或将其转换为类型。这是我的代码:

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

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>


我不知道如何添加弹头。我不想看到我试图显示它的子弹的可见ID。但我实际上不了解如何进行处理。我是新手,请帮助任何人。

瑞娜

看来您想让id在url中不可见,简单的方法是将Delete动作更改为post类型。

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>

控制器:

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

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

确保您的Delete.cshtml应该如下所示:

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

结果: 在此处输入图片说明

更新:

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

控制器:

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

app.UseEndpoints(endpoints =>
{               
      endpoints.MapControllerRoute(
             name: "default",
             pattern: "{controller=Home}/{action=Index}/{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);
    }
}

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在ASP.NET MVC Core应用程序(RC2)中显示项目版本

来自分类Dev

在RazorPages asp.net core 2_1中显示parentcategoryname

来自分类Dev

ASP.NET Core rc2中的Cookie

来自分类Dev

ASP.NET Core RC2中的网址重写

来自分类Dev

ASP.NET Core RC2中的网址重写

来自分类Dev

ASP.NET Core 2 razor 页面中的文件上传

来自分类Dev

使用ASP.NET Core RC2 404(而不是403)进行承载身份验证

来自分类Dev

在 ASP.NET Core 2 中使用令牌或 Open ID Connect 进行身份验证

来自分类Dev

加载表时显示用户名(存储在 ASP.Net Core Identity 系统中),而不是 ID

来自分类Dev

ASP Net Core 1 RC2 AccountController注入

来自分类Dev

asp.net core 2 Web API超时问题

来自分类Dev

是否发布了ASP.NET Core RC2?

来自分类Dev

如何从 Angular 2 访问 Asp.net Core Api

来自分类Dev

asp.net core 1.1 antiforgery with angular 2/4

来自分类Dev

带参数的 ASP.Net Core 2 Razor AJAX GET?

来自分类Dev

Asp.Net MVC Core 2 - 在 _Layout 上使用 ViewBag

来自分类Dev

AutoMapper Asp.Net Core 2:未映射的属性

来自分类Dev

无法添加对.net core类库asp.net core rc2的引用

来自分类Dev

ASP.NET Core 3.1如何使用Azure AD B2C返回401未经授权而不是质询

来自分类Dev

在MVC中显示URL Slug而不是ID

来自分类Dev

.NET Core RC2 applicationhost.config与ASP.NET .NET 4.6不兼容?

来自分类Dev

转换ASP.Net Core中的Open Id Connect声明

来自分类Dev

下拉列表显示主键而不是ASP.NET Core和Razor中的名称

来自分类Dev

asp.net core 2 web api 从 appsettings 设置托管 url

来自分类Dev

ASP.nET核心Web应用程序(.NET Core RC2)-为什么head标签中的项目显示在body标签中

来自分类Dev

ASP.NET MVC 6(ASP.NET Core或ASP.NET5)中的友好URL

来自分类Dev

ASP.NET Core 1.0 RC2中的“找不到类型或名称空间名称”

来自分类Dev

如何禁用ASP.NET Core rc2中的浏览器缓存?

来自分类Dev

如何在ASP.NET Core 1.0 RC2中加载程序集

Related 相关文章

  1. 1

    在ASP.NET MVC Core应用程序(RC2)中显示项目版本

  2. 2

    在RazorPages asp.net core 2_1中显示parentcategoryname

  3. 3

    ASP.NET Core rc2中的Cookie

  4. 4

    ASP.NET Core RC2中的网址重写

  5. 5

    ASP.NET Core RC2中的网址重写

  6. 6

    ASP.NET Core 2 razor 页面中的文件上传

  7. 7

    使用ASP.NET Core RC2 404(而不是403)进行承载身份验证

  8. 8

    在 ASP.NET Core 2 中使用令牌或 Open ID Connect 进行身份验证

  9. 9

    加载表时显示用户名(存储在 ASP.Net Core Identity 系统中),而不是 ID

  10. 10

    ASP Net Core 1 RC2 AccountController注入

  11. 11

    asp.net core 2 Web API超时问题

  12. 12

    是否发布了ASP.NET Core RC2?

  13. 13

    如何从 Angular 2 访问 Asp.net Core Api

  14. 14

    asp.net core 1.1 antiforgery with angular 2/4

  15. 15

    带参数的 ASP.Net Core 2 Razor AJAX GET?

  16. 16

    Asp.Net MVC Core 2 - 在 _Layout 上使用 ViewBag

  17. 17

    AutoMapper Asp.Net Core 2:未映射的属性

  18. 18

    无法添加对.net core类库asp.net core rc2的引用

  19. 19

    ASP.NET Core 3.1如何使用Azure AD B2C返回401未经授权而不是质询

  20. 20

    在MVC中显示URL Slug而不是ID

  21. 21

    .NET Core RC2 applicationhost.config与ASP.NET .NET 4.6不兼容?

  22. 22

    转换ASP.Net Core中的Open Id Connect声明

  23. 23

    下拉列表显示主键而不是ASP.NET Core和Razor中的名称

  24. 24

    asp.net core 2 web api 从 appsettings 设置托管 url

  25. 25

    ASP.nET核心Web应用程序(.NET Core RC2)-为什么head标签中的项目显示在body标签中

  26. 26

    ASP.NET MVC 6(ASP.NET Core或ASP.NET5)中的友好URL

  27. 27

    ASP.NET Core 1.0 RC2中的“找不到类型或名称空间名称”

  28. 28

    如何禁用ASP.NET Core rc2中的浏览器缓存?

  29. 29

    如何在ASP.NET Core 1.0 RC2中加载程序集

热门标签

归档