Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 具有继承、嵌套视图模型和局部视图的MVC复杂模型绑定_C#_Asp.net Mvc_Entity Framework_Asp.net Mvc 5 - Fatal编程技术网

C# 具有继承、嵌套视图模型和局部视图的MVC复杂模型绑定

C# 具有继承、嵌套视图模型和局部视图的MVC复杂模型绑定,c#,asp.net-mvc,entity-framework,asp.net-mvc-5,C#,Asp.net Mvc,Entity Framework,Asp.net Mvc 5,我无法将嵌套模型的值返回到控制器,它们都是空值 以下是简化的体系结构: //The viewModel being passed to the view public class RunnerIndexViewModel { public RegisterViewModel User { get; set; } public TrainerViewModel TrainerVM { get; set; } public RunnerBase Runner { get;

我无法将嵌套模型的值返回到控制器,它们都是空值

以下是简化的体系结构:

//The viewModel being passed to the view
public class RunnerIndexViewModel
{
    public RegisterViewModel User { get; set; }

    public TrainerViewModel TrainerVM { get; set; }

    public RunnerBase Runner { get; set; }

    [Display(Name = "AddContact", ResourceType = typeof(MyRessources))]
    public bool AddContact { get; set; }
}

public class RegisterViewModel
{
    // various simple type properties here
}

public class TrainerViewModel
{
    // various properties here
    public Unit unit { get; set; }

    public List<SelectListItem> ListStatut { get; set; }
}

public abstract partial class RunnerBase
{
    // entity framework class with associations
}

public class RedRunner : RunnerBase
{
    // entity framework class with associations
}

public class BlueRunner : RunnerBase
{
    // entity framework class with associations
}
视图PartialTrainer和PartialUser没有什么特殊之处,因此下面是PartialRunner视图,它从实体框架中获取基类:

@model RunnerBase

@* Show Various fields from RunnerBase ... *@

@if (Model is RedRunner)
{
    @* show properties specific to RedRunner *@
}
else if (Model is BlueRunner)
{
    @* show properties specific to BlueRunner *@
}   
我从控制器向Runner属性传递RedRunner或BlueRunner。所有viewModels的所有字段都显示得很好,但在提交表单时,我只获得AddContact值


如何获取其他ViewModel和Runner类的ViewModel的值?

问题在于使用partials。每次进入a部分时,模型上下文都会发生变化,因此Razor为您生成的输入没有考虑完整的属性路径。例如,如果要在主视图中执行以下操作:

@Html.EditorFor(m => m.TrainerVM.SomeProperty)
生成的HTML类似于:

<input type="text" name="TrainerVM.SomeProperty" />
<input type="text" name="SomeProperty" />
生成的HTML类似于:

<input type="text" name="TrainerVM.SomeProperty" />
<input type="text" name="SomeProperty" />
@Html.Partial("PartialTrainer", Model.TrainerVM, new ViewDataDictionary(ViewData)
{
    TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "TrainerVM" }
})