Reputation: 171
Im using a partial view, and i have some Razor code that will be used a lot of times in the partial view... Can i use partial views inside this partial view?
Or have a better way to do this?
When i try to do this:
this is the principal page:
@model List<GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo>
@{
ViewBag.Title = "Relatorio";
}
<div>
<div class="container">
<div class="row">
<div class="col-lg-8">
<input type="text" id="" name="" />
</div>
<div class="col-lg-4">
<div>
@Html.Partial("~/Areas/LOG/Views/Home/PhonePreview.cshtml", Model)
</div>
</div>
</div>
</div>
</div>
who uses a partial view:
@{
Layout = null;
}
<div>
<div style="border:1px solid black;font-size:20px;overflow:auto;">
@if (Model != null)
{
<div class="container" style="background-color:orangered;padding-top:5px;padding-bottom:5px;">
<div class="row">
<div class="col-sm-12">
@ViewBag.Relatorio
</div>
</div>
</div>
foreach (var campo in Model)
{
if (campo.Tipo == "Text")
{
@Html.Partial("~/Areas/LOG/Views/Home/text.cshtml", campo)
}
}
}
</div>
</div>
<style>
input[type=date]::-webkit-inner-spin-button {
-webkit-appearance: none;
display: none;
}
</style>
and this partial calls this another partial
<div class="container" style="padding-top:5px;padding-bottom:5px;">
<div class="row">
<div class="col-sm-4">
@model.Name:
</div>
<div class="col-sm-8" style="text-align:right;">
<input type="text" style="width:100%;" />
</div>
</div>
</div>
gives me an error:
'HtmlHelper<dynamic>' has no applicable method named 'RenderPartial' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax
regards!!
Rafael
Upvotes: 2
Views: 4444
Reputation: 218852
You are getting that error because your partial views are not strongly typed.
You need to make them strongly typed to the data you are passing in.
You are passing the Model of your principal page to the first partial view. Your Model is a list of Campo
. So your first partial view should also be strongly typed to that type (List<Campo>
).
Add this line as the first line in your first partial view (PhonePreview.cshtml
)
@model List<GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo>
Inside your PhonePreview.cshtml
partial view, you are looping through the items passed to it and calling the text.cshtml
partial view when your if condition returns true. Here you are passing a simple Campo
object to the text partial view. So it should be strongly typed to Campo
type.
Add this line as the first line in your first partial view (text.cshtml
)
@model GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo
. Also you should be accessing the Name property like Model.Name
, not model.Name
@model GolTripulacao.WebApi.Areas.LOG.Controllers.HomeController.Campo
<div class="col-sm-4">
@Model.Name
</div>
Upvotes: 4