How to render a partial view from a different model/controller?
asp.net-mvc-4, partial-views
Solution
I create viewmodel for my partialview, then pass its data. For example: my viewmodel
public class CompanyCreateViewModel
{
public Company Company { get; set; }
public IList<CompanyContact> CompanyContacts { get; set; }
public IQueryable<ContactType> ContactTypes { get; set; }
}
partialview
@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>
---
and View with calling 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>
----
Problem
I have the following partial view called _Categories residing in ~/Views/Category/_Categories: ``` @model IEnumerable<MyBlogSite.Models.BlogPostCategory> <ul> @foreach (var item in Model) { <li>@Html.DisplayFor(modelItem => item.Name)</li> } </ul> ``` I have the following Index view at ~/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> ... ``` In the space of the dashes (----) above is where I have been trying to figure out how to pass the model in. I cannot use Model.BlogPostCategory because it only accepts Model.BlogPost. I have also tried "model" with a lower-case "m" as per a couple of posts that I saw here.