Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to Partial View in ASP.NET Core

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?

like image 734
Miguel Moura Avatar asked Sep 07 '17 15:09

Miguel Moura


2 Answers

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>
like image 96
Win Avatar answered Sep 20 '22 13:09

Win


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.

like image 26
Ricardo Peres Avatar answered Sep 18 '22 13:09

Ricardo Peres