0

I have been tried to know an attribute routing system in ASP.NET Core. I have following codes and would like to know why my Save Method in controller does not trigger on form post:-

HTML code:-

 <form method="post" action="/Address/Save">
        <label asp-for="Street">Street:</label>
        <input type="text" asp-for="Street" />
        <label asp-for="City">City:</label>
        <input type="text" asp-for="City" />
        <input type="submit" value="Submit" />      
    </form>

My address controller code follow:-

public class AddressController : Controller
{
    public List<Address> addresses { get; set; } = new List<Address>();

    [HttpGet()]
    public IActionResult Create()
    {
        return View(new Address());
    }
    [Route("/Address/Save")]
    [HttpPost()]
    public IActionResult Save([FromBody] Address address)
    {

       //codes removed for brevity

    }
    public IActionResult Privacy()
    {
        return View();
    }     
}

startup routing configuration

 app.UseMvc(routes =>
  {
    routes.MapRoute(
    name: "default",
    template: "{controller=Address}/{action=Create}/{id?}");
  });
3
  • 1
    Remove [FromBody] attribute Commented Apr 10, 2019 at 14:25
  • Reference Customize model binding behavior with attributes Commented Apr 10, 2019 at 14:28
  • [Route()] attribute commonly used at over Controller name. Commented Apr 10, 2019 at 20:24

1 Answer 1

1

First problem: don't use action="url", use ASP.NET Core attributes, these generate the correct URL for you while also ensuring the AntiForgeryToken is present in the form:

<form asp-controller="Address" asp-action="Save">

Second problem: [FromBody] is used for sending data in the body of the request, most commonly as JSON, and you are using Form content.

public IActionResult Save(Address address)

Third problem: don't use both [Route] and [Http*], prefer using only one of them

[HttpPost("/Address/Save")]

Fourth problem: this configuration means that / will go to Address/Create, and /Home will go to /Home/Create, that is a very weird template:

template: "{controller=Address}/{action=Create}/{id?}");

I would suggest you to keep to the original Index action (or whatever you want to call it) and set your startup URL to /Address/Create.

template: "{controller=Address}/{action=Index}/{id?}");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.