2011-03-07 70 views
0

我觉得这很愚蠢,但我似乎无法在页面中获得局部视图渲染。填充局部视图

我创建了一个局部视图,即时试图加载到我的索引页面。我已经调用了我的pv _BusinessDetails,基本上它是一个返回一些客户数据的视图。

我的PV看起来像

@model MyMVC.Models.BusinessModel 
<div class="grid"> 

<div class="grid-header"> 
<div class="gh-l"></div> 
    <div class="gh-m">Business Details</div> 
<div class="gh-r"></div> 
</div> 

<div class="grid-row"> 
    <label class="labelBold">Busines Name</label> 
    <label>@Model.BusinesName</label> 
</div> 

</div> 

从我的索引页我想打电话给使用

@Html.Partial("_BusinessDetails") 

其失败,所以如果我添加

@Html.Partial("_BusinessDetails",new MyMVC.Models.BusinessModel()) 

局部视图光伏但是由于控制器没有被击中,因此没有数据。在我的控制器中,我试过了

public ActionResult _BusinessDetails() 
    { 
     return PartialView("_BusinessDetails"); 
    } 

public PartialViewResult _BusinessDetails() 
    { 
     return PartialView("_BusinessDetails"); 
    } 

但是他们都没有被击中。我做错了什么?

回答

2

当渲染局部视图并传递视图模型时,该视图模型应该已经被填充。使用@Html.Partial()时,不会调用控制器/操作方法。

既然您在您的主页上使用了这种强类型的局部视图,请考虑在您的HomeControllerIndex()方法中构建其视图模型。你的索引页也是强类型的吗?如果是这样,您可以将您的分视图的视图模型添加为索引页视图模型的属性,并在调用@Html.Partial()时传递该视图模型。

在您的索引页,它看起来是这样的:

@model MyMVC.Models.IndexViewModel 
<!-- some HTML here --> 
@Html.RenderPartial("_BusinessDetails", Model.BusinessModel) 

如果你的索引页不强类型,你可以使用ViewBag对象或者您可以在强类型MyMVC.Models.BusinessModel和使用@Html.RenderPartial("_BusinessDetails", Model) (虽然很简单,但可能会导致混淆)。

Rachel Appel有一个不错的blog post,如Mike Brind,如果你想了解更多信息。

0

这很棘手。我已经成功使用在主视图作为容器对象的模型:

class MainPageModel { 
    public BusinessDetailModel BusinessDetails { get; set; } 
    // ... 
} 

,然后刚好路过整个模型像@Html.Partial("_BusinessDetails", Model)我的部分景色。

0

当你写了这个,

@Html.Partial("_BusinessDetails",new MyMVC.Models.BusinessModel()) 

中的数据不会加载你的模型是空的,所以传递模型商业模式之前,之前填充它。