的RenderPartial,模型作为参数 [英] RenderPartial, model as argument

查看:299
本文介绍了的RenderPartial,模型作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个类型的错误,但我不明白为什么,我有一个观点,一个视图模型,一个PartialView和模型。

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

该视图的礼物有giftViewModel为模型。
giftViewModel包含型号LoginModel(登录)的一个实例。

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

该partialView LoginPopUp需要LoginModel为模型。
我试着礼物视图中呈现partialView LoginPopUp,它传递的身份登录模式。

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

和我得到这个错误:

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

下面是code:

GiftViewModel.cs

GiftViewModel.cs

    public class GiftViewModel
{

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

礼品/ Index.cshtml

Gift/Index.cshtml

@model GiftViewModel

@section content{

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

LoginPupUp.cshtml

LoginPupUp.cshtml

@model LoginModel
[...]

我真的不明白的地方,我错了......

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

推荐答案

您应该检查是否 Model.login!= NULL 的行

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

在情况下,它是平等的,该框架将通过模型形成父视图的 LoginPopUp ,这是 GiftViewModel 。这就是为什么你收到此错误,因为局部视图需要类型的模型项目 LoginModel

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

这篇关于的RenderPartial,模型作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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