来自视图组件的表单发布 [英] Form Post from View Component

查看:73
本文介绍了来自视图组件的表单发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个小型Web应用程序以测试新的ASP.NET Core MVC. 我实现了一个视图组件,该视图组件包含一个登录表单,需要将其插入到整个应用程序的各个位置.我的表单当前将数据发布到处理登录的普通Controller.

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?

我只想向用户提供用于再次输入其凭据的相同站​​点,但会出现验证错误.有什么方法可以找出查看表单帖子的来源吗?还是更好的方法是,在ASP.NET Core MVC中,有没有任何标准的方法可以将表单作为视图组件来处理?

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?

推荐答案

如果您继承自ViewComponent,则可以访问ViewContext属性,该属性包括有关路线数据的所有内容,包括动作和控制器.然后,将IUrlHelperFactory注入到ViewComponent中(通过构造函数,然后存储为私有字段),并通过从工厂获取IUrlHelper(传递ViewContext)并调用Action()方法来重新创建URL.在上面.

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

这篇关于来自视图组件的表单发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆