Read object values in Razor

2019-08-16 20:29发布

问题:

I have a ViewData that contains a string like that.

{ Param1 = "1", Param2 = "2", Param3 = "3" }

I'm setting it to an object razor variable, but I can't read this values like @myVar.Param1.

@{
    object myParameters = ViewData["parameters"];
}

I know how to do that in JS, but not in Razor. What is the best way to do this?

Regards

回答1:

Since you are using object of anonymous type defined elsewhere (in controller), you cannot have strong typed access to the properties. However you should be able to use Eval:

ViewData.Eval("parameters.Param1")

Although I encourage you to consider defining a class for this model.



回答2:

myParameters should be dynamic:

dynamic myParameters = ViewData["parameters"];