Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

asp.net mvc - How to pass model to partial view

I have two view models:

public class ParentViewModel
    {
        public Id { get; set; }
        .....
        public ChildViewModel Child{ get; set; }
    }

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

Controllers:

    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)

and _Partial

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

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

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

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

question from:https://stackoverflow.com/questions/21172595/how-to-pass-model-to-partial-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same issue as the OP. From one of the comments, I realized that the second parameter shouldn't be null, i.e from

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

If Model.Child is null, then Model is passed instead of Model.Child. If there will be cases when the second parameter is null, then you will have to check first in your code and maybe pass an initialized Child as the second parameter. Something like this

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...