How to pass model to partial view

后端 未结 3 1155
悲哀的现实
悲哀的现实 2020-12-16 09:06

I have two view models:

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


        
相关标签:
3条回答
  • 2020-12-16 09:46

    You could return PartialView("...") from a Controller instead, and call the action from the Index view.

    Controllers:

    public ActionResult Index()
    {
        .... <some code>
        return View("NewIndex", ParentViewModel);
    }
    
    public ActionResult Partial(ChildViewModel cvm)
    {
        var vm = cvm ?? new ChildViewModel(); //if cvm from the parent view is null, return new cvm
        return PartialView("_Partial", vm) //return partial view
    }
    
    [HttpPost]
    public ActionResult PartialAction(ChildViewModel childView)
    {
        return RedirectToAction("Index");
    }
    

    And Index

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

    Alternatively, you could initialize ParentViewModel in the Index() public ActionResult Index()

    {
        .... <some code>
        return View("NewIndex", new ParentViewModel{Child = new ChildViewModel});
    }
    
    0 讨论(0)
  • 2020-12-16 10:05

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

    @Html.Partial("_Partial", new ChildViewModel ())
    
    0 讨论(0)
  • 2020-12-16 10:09

    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())
    
    0 讨论(0)
提交回复
热议问题