Home > Software design >  Body mapping for .net core
Body mapping for .net core

Time:05-04

I currently have an endpoint as follows in the backend:

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

And cshtml:

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

This correctly maps to my Index endpoint in the code behind when the button is pressed, but currently all of these parameters are visible in the query string of the URL. How would I go about implementing something similar, but via a POST and the body holding the contents of the above and it mapping to the endpoint?

Thanks

CodePudding user response:

<a>xx</a> can only send get request, asp-route-xx will map the value to route, So if you don't want to do that, You can use <form></form>to implementing something similar.

Demo:

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

I'm not sure if you have to implement it with <a></a> and put data in RequestBody, If your thinking is like this, You can use ajax to achieve it. But if you just want to achieve simple model binding with post request,The above demo is ok.

  • Related