Access Parent Model from partial view

前端 未结 5 2046
半阙折子戏
半阙折子戏 2021-01-07 22:00

I\'m asking because the partial view I will create is blank, with the purpose of creating a new child entity. I just need a quick, regardless if dirty, way to access the Pa

5条回答
  •  甜味超标
    2021-01-07 22:31

    You cannot access the parent model from a partial view unless you pass some value to this partial as parameters when rendering it. For example in your main view:

    @model MyViewModel
    ...
    @Html.Partial("_myPartial", new ViewDataDictionary(new { id = Model.Id }));
    

    and then inside your partial you could access the Id:

    @ViewBag.Id

    Of course this is a pretty lousy way of passing data to a partial view. The correct way is to use a strongly typed view model.

提交回复
热议问题