Pass parameter to Partial View in ASP.NET Core

扶醉桌前 提交于 2019-11-30 13:52:54

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.

When you do new { File = "file.pdf" }, you are passing an object that contains an attribute file. Since this is of type object, you can't access any of its variables in c# directly. There some ugly codes to access a fields from an object such as the one that can be found here: C# .NET CORE how to get the value of a custom attribute?

However in this case the most recommended way (for safety) is the create a class and pass an object of that class.

So if you create the following class:

public class MyFileInfo{
    public string File { get; set }
}

Then you can create your object by passing:

@Html.Partial("Form", new MyFileInfo{ File = "file.pdf" })

In your partial view, at the beginning, define your model class

@model MyFileInfo

Then in the same file you will now be able to access

@Model.File
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!