Body .net 核心的映射

Body mapping for .net core

我目前在后端有如下端点:

public async Task<IActionResult> Index(string id, string test, string test2)
{
    //some code
}

和 cshtml:

            <a asp-action="Index" 
               asp-route-id="@ViewData["id"]" 
               asp-route-test="@ViewData["test"]"
               asp-route-test="@ViewData["test2"]"
               >Submit</a>

当按下按钮时,这正确地映射到我在后面的代码中的索引端点,但目前所有这些参数在 URL 的查询字符串中都是可见的。我将如何实现类似的东西,但是通过 POST 和 body 保存上面的内容并将其映射到端点?

谢谢

<a>xx</a>只能发送get请求,asp-route-xx会将值映射到路由,所以如果你不想这样做,你可以使用<form></form>来实现一些东西相似。

演示:

//You can put your properties into a model for passing of values easily

public class TestModel
    {
        public int Id { get; set; }
        public string Test { get; set; }
        public string Test2 { get; set; }
    }


//use <form> to submit the post value

@model TestModel

    <form method="post">
        <input type="hidden" asp-for="Id" value="@ViewData["id"]" />
        <input type="hidden" asp-for="Test" value="@ViewData["test"]" />
        <input type="hidden" asp-for="Test2" value="@ViewData["test2"]" />
        <button type="submit">sumit</button>
    </form>

不知道你是不是一定要用<a></a>实现,把数据放在RequestBody里,如果你的想法是这样的,可以用ajax来实现。但是如果你只是想用post请求实现简单的模型绑定,上面的demo是可以的。