RenderPartial, model as argument

你。 提交于 2019-12-23 17:24:32

问题


I get a type error but I don't understand why, I have a View, a ViewModel, a PartialView and a Model.

The view gift has giftViewModel as model. giftViewModel contain an instance of the Model LoginModel (login).

The partialView LoginPopUp takes a LoginModel as model. I try to render the partialView LoginPopUp within the gift view, passing it login as model.

And I get this error :

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

Here is the code:

GiftViewModel.cs

    public class GiftViewModel
{

    public LoginModel login { get; set; }
    [...]
}

Gift/Index.cshtml

@model GiftViewModel

@section content{

  @{Html.RenderPartial("LoginPopUp", Model.login);}
}

LoginPupUp.cshtml

@model LoginModel
[...]

I really don't understand where I am wrong...


回答1:


You should check whether Model.login != null in the line

@{Html.RenderPartial("LoginPopUp", Model.login);}

In case it is equal, the framework will pass model form the parent view to the LoginPopUp, which is type of GiftViewModel. That is why you are getting this error, because the partial view requires a model item of type LoginModel.

So either initialize the login property before that, say in controller, or do something like

@{Html.RenderPartial("LoginPopUp", Model.login ?? new LoginModel());}


来源:https://stackoverflow.com/questions/21241227/renderpartial-model-as-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!