坐落在F#上ViewBag动态对象的属性 [英] Set a property on ViewBag dynamic object in F#

查看:109
本文介绍了坐落在F#上ViewBag动态对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#这种操作方法:

I have this action method in C#:

  public ActionResult Index() {
      ViewBag.Message = "Hello";
      return View();
  }

和这种观点(Index.cshtml):

And this view (Index.cshtml):

  <h2>@ViewBag.Message</h2>

这将产生预期的你好的页面上。

And this produces the expected "Hello" on the page.

我想做的事情在F#中的控制器。我试过

I want to do the controller in F#. I've tried

type MainController() =
  inherit Controller()
  member x.Index() =
    x.ViewBag?Message <- "Hello"
    x.View()

这产生错误信息方法或对象的构造op_DynamicAssignment未找到。

And this produces the error message "Method or object constructor 'op_DynamicAssignment' not found".

我看了一些F#code样本进行动态操作者,我看不到任何东西,这比描述的几页和code多行短。他们似乎过于笼统只是这个属性二传手。

I've looked at some of the F# code samples for the dynamic operator, and I can't see anything that's shorter than several pages of description and many lines of code. They seem to be too general for just this property "setter".

推荐答案

ViewBag 属性只是一个公开的包装在的ViewData 集合作为类型的属性动态,以便它可以动态地从C#(使用属性集语法)来访问。你可以使用实施基于DLR做到这一点(见<一href=\"http://stackoverflow.com/questions/5057672/looking-for-robust-general-op-dynamic-implementation\">this在SO 讨论),但它更容易定义运营商直接将数据添加到的ViewDataDictionary (这是由的ViewData 属性公开):

The ViewBag property is just a wrapper that exposes the ViewData collection as a property of type dynamic, so that it can be accessed dynamically from C# (using property set syntax). You could use implementation of ? based on DLR to do that (see this discussion at SO), but it is easier to define ? operator that adds data directly to ViewDataDictionary (which is exposed by the ViewData property):

let (?<-) (viewData:ViewDataDictionary) (name:string) (value:'T) =
  viewData.Add(name, box value)

那么你应该能够编写

Then you should be able to write

x.ViewData?Message <- "Hello"

这篇关于坐落在F#上ViewBag动态对象的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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