Set a property in a dynamic ViewBag in F #

I have this action method in C #:

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

And this view (Index.cshtml):

  <h2>@ViewBag.Message</h2> 

And this leads to the expected "Hello" on the page.

I want to make a controller in F #. I tried

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

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

I looked through some of the F # code examples for a dynamic statement, and I don't see anything shorter than a few description pages and many lines of code. They seem too general for this setter property.

+6
source share
2 answers

The ViewBag property is just a wrapper that provides the ViewData collection as a property of type dynamic , so that it can be dynamically retrieved from C # (using the syntax of a set of properties). Can you use the implementation ? DLR based for this (see this discussion in SO ), but is it easier to define an operator ? which directly adds data to the ViewDataDictionary (which is displayed using 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" 
+10
source

Instead

 x?ViewBag <- "Hello" 

Try:

 x.ViewBag?Message <- "Hello" 
+1
source

Source: https://habr.com/ru/post/901603/


All Articles