Search code examples
asp.net-coremodel-bindingasp.net-core-viewcomponent

Form containing with ViewComponent


I couldn't figure out how to use ViewComponent inside form

The form is rendered correctly (value in the dropdown), but the model binding, when posting form, fail

This is the view

<form asp-action="" method="post">
    <div asp-validation-summary="All"></div>
    <div class="row">
        <vc:periodi model="@(Model.Periodi)"></vc:periodi>
    </div>

This is the ViewComponent

<div class="col-2">
@(Html.Kendo().DropDownListFor(a => a.Anno)
                    .DataTextField("Text")
                    .DataValueField("Value")
                    .BindTo(Model.Anni)
                    .HtmlAttributes(new { style = "width: 100%" }))

No matter what I choose in the dropdown, the variable Anno inside the Object Periodi of the Model is null

I checked the rendered HTML

<input id="Anno" name="Anno" ...

I think, based on my experience with MVC, that should be something like "Periodi.Anno" for the model binder to work. Any suggestion?


Solution

  • As your experience, the name should be Periodi.Anno to bind the ViewComponent property.

    As my test with input tag like below:

    <input asp-for="Name" name="MVCSubModel.Name" class="form-control" />
    

    I suggest you try :

    @(Html.Kendo().DropDownListFor(a => a.Anno)
                    .DataTextField("Text")
                    .DataValueField("Value")
                    .BindTo(Model.Anni)
                    .HtmlAttributes(new { style = "width: 100%"; name = "Periodi.Anno" }))