如何通过模型局部视图 [英] How to pass model to partial view

查看:155
本文介绍了如何通过模型局部视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个视图模型:

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");
    }

和看法:
指数

And views: Index

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

和_Partial

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

当我试图打开索引页,我得到了一个错误:

When I'm trying to open Index page I've got an error:

传递到字典中的模型产品类型ParentViewModel',但这需要字典类型的模型项目ChildViewModel。

The model item passed into the dictionary is of type 'ParentViewModel', but this dictionary requires a model item of type 'ChildViewModel'.

为什么试图通过ParentViewModel而不是ChildViewModel。我做错了吗?

Why it tries to pass ParentViewModel instead of ChildViewModel. What I'm doing wrong?

推荐答案

答案是,需要一个空的对象传递给部分,如

The answer is that needs to pass an empty object to Partial, like

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

这篇关于如何通过模型局部视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆