2

我在 ~/Views/Category/_Categories 中有以下名为 _Categories 的局部视图:

@model IEnumerable<MyBlogSite.Models.BlogPostCategory>

<ul>
@foreach (var item in Model)
{
    <li>@Html.DisplayFor(modelItem => item.Name)</li>
}
</ul>

我在 ~/Views/Blog/Index.cshtml 有以下索引视图:

@model IEnumerable<MyBlogSite.Models.BlogPost>

@{
   ViewBag.Title = "Index";
 }

@Html.RenderPartial("~/Views/Category/_Categories.cshtml", ---- );

<p>
   @Html.ActionLink("New Blog Post", "Create")
</p>
<table>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Title)
    </th>       
    ...

在上面的破折号 (----) 的空间中,我一直试图弄清楚如何传递模型。我不能使用 Model.BlogPostCategory,因为它只接受 Model.BlogPost。根据我在这里看到的几篇文章,我还尝试了带有小写“m”的“模型”。

4

1 回答 1

7

我为我的partialview创建viewmodel,然后传递它的数据。例如:我的视图模型

public class CompanyCreateViewModel
{
    public Company Company { get; set; }
    public IList<CompanyContact> CompanyContacts { get; set; }
    public IQueryable<ContactType> ContactTypes { get; set; }
}

局部视图

@model Invoice.Model.HelperClasses.CompanyCreateViewModel
---
<div class="editor-field">
        @Html.TextBoxFor(model => model.Company.FullName)
        @Html.ValidationMessageFor(model => model.Company.FullName)
        @Html.TextBoxFor(model => model.Company.ShortName)
        @Html.ValidationMessageFor(model => model.Company.ShortName)
        @Html.TextBoxFor(model => model.Company.TIN)
        @Html.ValidationMessageFor(model => model.Company.TIN)
    </div>
    <div class="editor-field">
        @Html.TextBoxFor(model => model.Company.Address.Country)
        @Html.TextBoxFor(model => model.Company.Address.City)
        @Html.TextBoxFor(model => model.Company.Address.Street)
    </div>    
    ---

并通过调用partialview查看

@model Invoice.Model.HelperClasses.CompanyViewModel
---
<div id="CompanyCreateModal" class="modal hide fade">
    @{Html.RenderPartial("CompanyParts/CompanyCreateModal", new Invoice.Model.HelperClasses.CompanyCreateViewModel() { ContactTypes = Model.ContactTypes });
    }
</div>
----
于 2013-07-13T07:01:49.280 回答