Search code examples
asp.net-mvcrazorasp.net-core-viewcomponent

Form Post from View Component


I'm building a small web application to test the new ASP.NET Core MVC. I implemented a View Component that comprises a login form that I need to insert into various places throughout the application. My form currently posts data to a normal Controller that handles the login.

Now given that the user provided wrong login information I want to add an error message to the model state and display it under my form, like normal validation. But the thing is since the view component can be integrated in all kinds of places, how do I find out where the form post came from?

I want to render the same site the user used to enter his credentials again only with the validation errors. Is there any way to find out which View the form post came from? Or better is there any standard way to handle forms as view components in ASP.NET Core MVC?


Solution

  • If you have inherited from ViewComponent, you have access to the ViewContext property, which includes everything about the route data, including action and controller. Then, inject IUrlHelperFactory into your ViewComponent (via the constructor, then store as a private field), and recreate the url by getting an IUrlHelper from the factory (passing in the ViewContext) and calling the Action() method on it.

    public class LoginViewComponent : ViewComponent {
        public LoginViewComponent(IUrlHelperFactory factory) {
            this.factory = factory;
        }
        private IUrlHelperFactory factory;
    
        public void Invoke() {
            IUrlHelper helper = factory.GetUrlHelper(ViewContext);
            helper.Action(); // returns url to the current controller action
        }
    }