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

Can I submit MVC6 view component?


Can I submit form inside view component somehow? I know it is not possible for partial views. View component has its own controller, so the goal of this question is if I can use this controller for submitting form rendered by component view.

It is not mentioned in MVC6 view components docs. So it is not possible, I guess, but maybe I'm wrong :)


Solution

  • Similar to partial views, view components can also render you some HTML. So as long as the view rendered by your view component has a valid form tag in it, Yes, you can submit forms.

    @model YourNamespace.LoginVM
    <form asp-controller="Home" asp-action="Login">
        <input asp-for="Name" />
        <input asp-for="Password" />
        <input type="submit" />
    </form>
    

    You need to make sure that you have a Login action method in HomeController

    [HttpPost]
    public ActionResult Login(LoginVM model)
    {
       //do something :)
    }
    

    The important thing to remember is, You should not be calling this view component inside another form tag. The general rule is, you should not be nesting forms.

    <form id="main-form" asp-controller="main" asp-action="submit" method="post">
        <input asp-for="LocationName" />
        <input type="submit"  />
    </form>
    
    @Component.Invoke("Login")