如何访问传递到局部视图的匿名类型的对象吗? [英] How do I access an anonymously-typed object passed into a partial view?

查看:104
本文介绍了如何访问传递到局部视图的匿名类型的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个网页的一些参数(一对夫妇的字符串)传递给在主网页被渲染的局部视图。要做到这一点,我传递一个匿名类型的对象,它不断给我一个RuntimeBinderException。鉴于我已经试过,我并不感到惊讶中得到错误,但我不知道还有什么尝试。

I'm trying to pass some parameters (a couple of strings) from a page to a partial view that is to be rendered in the main page. To do this, I'm passing an anonymously typed object, which keeps giving me a RuntimeBinderException. Given what I've tried, I'm not surprised to be getting the error, but I don't know what else to try.

视图\\首页\\ PageWithPartialView.cshtml

@Html.Partial("DynamicPartialView", new { paramFromPageToPartialView = "value" })

视图\\共享\\ DynamicPartialView.cshtml

@model dynamic // Doesn't make a difference

@{
    // This is where I need to access and display the parameters 
    // passed from the main page

    // Throws RuntimeBinderException
    // Cannot apply indexing with [] to an expression of type 'object'
    var try1 = Model["paramFromPageToPartialView"];

    // Throws RuntimeBinderException
    // 'object' does not contain a definition for 'paramFromPageToPartialView'
    var try2 = Model.paramFromPageToPartialView;
}

如果局部视图不这样做的方式,我愿意。局部视图有几百行code的生产,所以定制HtmlHelpers似乎不便于管理我。

If partial views aren't the way to do this, I'm open. The partial view has a couple hundred lines of code to produce, so custom HtmlHelpers don't seem manageable to me.

推荐答案

ViewBag 旨在解决这类问题。而不是消耗 paramFromPageToPartialView 在部分从模式,从消费到 ViewBag

The ViewBag is designed to solve this kind of problem. Rather than consuming paramFromPageToPartialView in your partial from the Model, consume it from the ViewBag:

视图\\首页\\ PageWithPartialView.cshtml

@{ViewBag.paramFromPageToPartialView = "value";}
@Html.Partial("DynamicPartialView")

视图\\共享\\ DynamicPartialView.cshtml

@model dynamic // Doesn't make a difference

@{
    var try3 = ViewBag.paramFromPageToPartialView;
}

这篇关于如何访问传递到局部视图的匿名类型的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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