asp.net-mvc – 如何将模型传递给部分视图

我有两个视图模型:
public class Parentviewmodel
    {
        public Id { get; set; }
        .....
        public Childviewmodel Child{ get; set; }
    }

public class Childviewmodel
    {
        public ChildId { get; set; }
        .....
    }

控制器:

public ActionResult Index()
        {
            .... <some code>
            return View("NewIndex",Parentviewmodel);
        }

    [HttpPost]
    public ActionResult PartialAction(Childviewmodel childView)
    {
        return RedirectToAction("Index");
    }

意见:
指数

@model Parentviewmodel
....
@Html.Partial("_Partial",Model.Child)

和_Partial

@model Childviewmodel
... do some stuff with child model

当我尝试打开索引页面时,我有一个错误

传入字典的模型项目的类型为“Parentviewmodel”,但此字典需要一个类型为“Childviewmodel”的模型项目.

为什么它尝试通过Parentviewmodel而不是Childviewmodel.我做错了什么?

解决方法

我和OP有同样的问题.从其中一个意见中,我意识到第二个参数不应该为null,即从
@model Parentviewmodel
@Html.Partial("_Partial",Model.Child)

如果Model.Child为空,则传递Model而不是Model.Child.如果第二个参数为空,那么您将首先检查代码,然后将初始化的Child作为第二个参数传递.这样的东西

@Html.Partial("_Partial",new Child())

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....