3

I'm fairly new to razor, kind of muddling my way through it to finish off some changes I made to the underlying c# code, and I'm running into a problem.

I need to use a settings property on an underlying object to get the correct configuration file to pull an image location from. I'm trying to change a hardcoded image into a configurable one.

What I have so far:

else
{
@{ 
     var prefix = Model.GetNameSpaceFromSettings();
     var configImgs = ChartColors.GetImgs(prefix);
}
<div style='float:left;'>
<img src='@Url.Content(Model.ComparisonChart(300, 250, false))' border='0' alt=''/>   
<p></p> 
<table width='295' cellpadding='2' cellspacing='1' border='0' class='summarygridtablebackground' align="left">                       
<tr class='summarygridbackground'>
<td>
<div style="float:left; width:125px;"><img src='@configImgs.MyImg' border='0'></div>//This is where I'm working
</td>
</tr>
//a few more rows where I'm trying to eventually do the same thing
</table>
</div>
}

This doesn't work, with the message "The name 'configImgs' does not exist in the current context."

I read in another question that a common solution to scope problems was to put the variables into an @functions section, so I tried that, and it ended up looking like this:

else
{
@functions{ 
      string prefix = Model.GetNameSpaceFromSettings();
      Images configImgs = ChartColors.GetImgs(prefix);
}

This one fails with a message pair, "An object is required for the non-static field, method, or property 'System.Web.Mvx.WebViewPage.Model.get" (I tried referencing it with 'this' as well, and it said that 'this' was not available in the current context) and "A field initializer cannot reference the non-static field, method, or property 'ASP.Myfile.prefix'"

I could really use some help here, thanks.

4

1 に答える 1

13

最初の@{}ブロック内で変数を宣言してみてください。これで、ビュー内のどこでも変数を使用できるようになります。

于 2012-08-29T19:39:10.653 に答える