Read object values in Razor

2019-08-16 20:13发布

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

2条回答
够拽才男人
2楼-- · 2019-08-16 20:37

myParameters should be dynamic:

dynamic myParameters = ViewData["parameters"];

查看更多
Bombasti
3楼-- · 2019-08-16 20:50

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.

查看更多
登录 后发表回答