Form Post from View Component

醉酒当歌 提交于 2020-02-04 05:04:42

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/37785144/form-post-from-view-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!