On an ASP.NET Core 2.0 application I need to render a partial view and pass a few parameters:
@Html.Partial("Form", new { File = "file.pdf" })
On the partial view I tried to access it using:
@Model.File
And I get the error:
RuntimeBinderException: 'object' does not contain a definition for 'File'
If I simply use on my partial:
@Model
I get the following printed on the page:
{ File = file.pdf }
So there the model is being passed and there is a property File in it.
So what am I missing?
You are passing untyped (anonymous type) data to partial view. You cannot use @Model.File
. Instead, you will need to use ViewData's Eval method to retrieve the value.
@ViewData.Eval("File")
Traditional approach is to create a strongly typed ViewModel class, and pass it to the partial view. Then you can access it as @Model.File
.
public class SampleViewModel
{
public string File { get; set; }
}
@Html.Partial("Form", new SampleViewModel { File = "file.pdf" })
Inside Partial View,
@model SampleViewModel
<h1>@Model.File</h1>
You should have dynamic
as the model of your partial view, this way, you can pass everything - like your anonymous object - and it will just work. Add:
@model dynamic
To the Form.cshtml file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With