将参数传递给ASP.NET Core中的部分视图 [英] Pass parameter to Partial View in ASP.NET Core

查看:457
本文介绍了将参数传递给ASP.NET Core中的部分视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET Core 2.0应用程序上,我需要呈现部分视图并传递一些参数:

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

我得到了错误:

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 } 

因此,正在传递模型,并且其中包含属性File.

So there the model is being passed and there is a property File in it.

那我想念什么?

推荐答案

您要将无类型的(匿名类型)数据传递到局部视图.您不能使用@Model.File.相反,您将需要使用ViewData的Eval方法来检索值.

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")

传统方法是创建一个强类型的 ViewModel 类,并将其传递给部分视图.然后,您可以作为@Model.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" })

内部局部视图,

@model SampleViewModel

<h1>@Model.File</h1>

这篇关于将参数传递给ASP.NET Core中的部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆