I am having a trouble with binding a value of partial view model to main view model. I am not sure what I am doing wrong but any hint would be helpful.
ViewModels
public class ParentViewModel
{
public int ParentId { get; set; }
public int ParentName { get; set; }
public ChildViewModel childViewModel { get; set; }
}
public class ChildViewModel
{
public bool HasChild { get; set; }
}
Razor view
@await Html.PartialAsync("_ChildViewPartial", Model.childViewModel)
Child Partial View
@model ChildViewModel
<input asp-for="@Model.HasChild"
asp-error-class="error"
class="input"
id="HasChild"
autocomplete="off"
type="checkbox"
value="@true">
<label class="checkboxes" for="HasChild">
Do you have child?
</label>
Now problem what I am facing is value of HasChild is always false in a post action.
If I include the code of child view model in a main view and use
asp-for="@Model.ChildViewModel.HasChild"
for check box then it works.
you can change view model
public class ParentViewModel:ChildViewModel
{
public int ParentId { get; set; }
public int ParentName { get; set; }
}
in this case child model could be the same
or just add HasChild to Parent. Why not?
public class ParentViewModel
{
public int ParentId { get; set; }
public int ParentName { get; set; }
public bool HasChild { get; set; }
}
in this case your child view model needs to be changed to parent
@model ParentViewModel
<input asp-for="HasChild"
....
but in both cases your main view should be the same like this, it is very important
<partial name="_ChildViewPartial" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.