[英]ViewModel of Partial View Not Binding to that of main ViewModel
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.现在我面临的问题是 HasChild 的值在后期操作中始终为 false。
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.或者只是将 HasChild 添加到父级。 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" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.