Reputation: 29
Problem resolved: I found a reusable solution. Thank you everyone for your help.
I'm frustrated and don't know what I'm doing. I'm attempting to build a webpage and one of the things I'm trying to do is cut down on code. In order to do so, I need to create a method, I know extensively about methods from Java, but not when trying to write C# in ASP.NET using razor syntax. The problem I'm facing is my @helper refuses to access the global hash table "dictionary". I've tried a lot of different things and have decided to turn to stackoverflow for help. Thanks in advance.
UPDATES:
Error Message is "CS0103: The name 'dictionary' does not exist in the current context"
I need a hashtable because I'm pulling from a database, checking to see if its null, if yes, replacing it with an empty string, then pushing it to a table. So if I could learn how to do it in this fashion, it would work best, I think?
<!doctype html>
@using System;
@using System.Collections.Generic;
@using System.Collections;
@using System.Linq;
@{
var dictionary = new Dictionary<string, object>();
dictionary.Add("fName", returnString100.FRSTNAME.Trim());
@helper printOut(string toBePrinted) {
object curValue;
if(dictionary.TryGetValue(toBePrinted, out curValue)) {
return curValue;
}
}
}
<table>
<tr>
<td>First Name:</td><td>@{ printOut("fName"); }</td>
</tr>
</table>
Upvotes: 1
Views: 336
Reputation: 401
While philosophically I agree with the others that you might want to encapsulate this in a class, here's how you can do this in Razor with a view:
<!doctype html>
@using System;
@using System.Collections.Generic;
@using System.Collections;
@using System.Linq;
@{
var dictionary = new Dictionary<string, object>();
dictionary.Add("fName", returnString100.FRSTNAME.Trim());
Func<string, object> PrintOut = delegate(string toBePrinted)
{
object curValue;
if (dictionary.TryGetValue(toBePrinted, out curValue))
return curValue;
return "";
};
}
<table>
<tr>
<td>First Name:</td><td>@PrintOut("fName").ToString()</td>
</tr>
</table>
Upvotes: 1