访问视图中的动态匿名类型时,RuntimeBinderException [英] RuntimeBinderException when accessing dynamic anonymous type in view

查看:273
本文介绍了访问视图中的动态匿名类型时,RuntimeBinderException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习/修补asp.net时遇到了一个奇怪的异常。



我试图显示这样的部分视图:

  @ Html.Partial(_ PartialView,new {Action =Foo})

当我'尝试使用

  //抛出Microsoft.Csharp.RuntimeBinder.RuntimeBinderException 
string throwsException = Model。行动;

a RuntimeBinderException为消息


'object'不包含'Action'的定义


被抛出。

奇怪的是,这条线工作正常:

  //这行工作正常
string works =((型)Model.GetType())的getProperty( 行动)的GetValue(型号)。

这个行为让我很困惑,我宁愿避免使用这个解决方法。另外我不认为问题是匿名类型是内部的因为VS2013中ASP.NET Project的MVC模板成功完成:





那么这里发生了什么?

解决方案>


那么这里发生了什么?


你的部分视图是弱键入的。你没有一个 @model 的定义。因此,默认情况下是对象,显然没有一个 Action 属性。



正确的解决方法是定义一个视图模型:

  public class MyViewModel 
{
public string Action {get;组;
}

您的部分视图将被强制输入:

  @model MyViewModel 
@ {
string throwsException = Model.Action;
}

,将由主视图传递:

  @ Html.Partial(_ PartialView,new MyViewModel {Action =Foo})
pre>

另一个可能性(我个人不喜欢依赖于运行时绑定)是在部分视图中使用动态模型:

  @model dynamic 
@ {
string throwsException = Model.Action;
}

然后,您可以在调用时传递匿名对象: / p>

  @ Html.Partial(_ PartialView,new {Action =Foo})


I've encountered a strange anomaly while learning/tinkering with asp.net.

I'm trying to show a partial view like this:

@Html.Partial("_PartialView", new { Action = "Foo" })

When I'm trying to access Action with

// Throws Microsoft.Csharp.RuntimeBinder.RuntimeBinderException
string throwsException = Model.Action; 

a RuntimeBinderExceptionis with the message

'object' does not contain a definition for 'Action'

is thrown.
The strange thing is that this line works fine:

// This line works fine
string works = ((Type)Model.GetType()).GetProperty("Action").GetValue(Model);

This behavior puzzles me quite a bit and I'd rather avoid using this workaround. Also I don't think the problem is anonymous types being internal because the MVC template for ASP.NET Project in VS2013 does this successfully:

So what happened here?

解决方案

So what happened here?

Your partial view is weakly typed. You do not have a @model definition for it. So by default it is object which obviously doesn't have an Action property.

The correct way to solve this is to define a view model:

public class MyViewModel
{
    public string Action { get; set; }
}

that your partial view will be strongly typed to:

@model MyViewModel
@{
    string throwsException = Model.Action; 
}

and which will be passed by the main view:

@Html.Partial("_PartialView", new MyViewModel { Action = "Foo" })

Another possibility (which personally I don't like as it relies on runtime binding) is to use a dynamic model in the partial view:

@model dynamic
@{
    string throwsException = Model.Action; 
}

and then you will be able to pass an anonymous object when calling it:

@Html.Partial("_PartialView", new { Action = "Foo" })

这篇关于访问视图中的动态匿名类型时,RuntimeBinderException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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