Click here to Skip to main content
14,868,283 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Dictionary which is populated with Key/Value pair data.

When the Key is found in the Dictionary, the corresponding Value is displayed.
In turn the Dictionary item is removed.
But when it is removed the return of True or False is being rendered to client side.

Here is cut down version of the code used to represent the issue:
Razor
@{
	Dictionary<String, String> KeyValuePairList = new Dictionary<String, String>();
	KeyValuePairList.Add("Key01", "Value01");
	String TempValue = "";
}
<div>
	@if (KeyValuePairList.TryGetValue("Key01", out TempValue)) {
		@TempValue
		@KeyValuePairList.Remove("Key01")
	}
	else {
		@:Value0001
	}
</div>

Here is the generated HTML:
HTML
<div>Value01True</div>


What I have tried:

Here are some of the ways I have tried.
HTML
@if...
	@(KeyValuePairList.Remove("Key01"))
...

OR

@{
...
	bool TempBool = false;
}
...
@if...
	@(TempBool = KeyValuePairList.Remove("Key01"))
...

Same render:
HTML
<div>Value01True</div>


HTML
@if...
	if (@KeyValuePairList.Remove("Key01")) { }
OR
	@(KeyValuePairList.Remove("Key01")?"":"")
...

Desired render, but using additional if statement:
HTML
<div>Value01</div>


HTML
@if...
	<!--@KeyValuePairList.Remove("Key01")-->
...

Generated html with comment of True, but does not display in final browser view:
HTML
<div>Value01<!--True--></div>


Now the question is, is how to stop the return value being rendered to the final HTML.
Is there a standard way/best practice way of doing it?
If you can point me to source material or a solution, that would be great.
Posted
Updated 5-Aug-16 3:31am

1 solution

C#
@if (KeyValuePairList.TryGetValue("Key01", out TempValue)) {
    @TempValue
    @KeyValuePairList.Remove("Key01")
}
else {
    @:Value0001
}

The "@" means to render the output, so you are rendering the output of KeyValuePairList.Remove, which returns True if something has been removed, so that is where your "True" is coming from. Instead you want to just run the code and not render the output

C#
@if (KeyValuePairList.TryGetValue("Key01", out TempValue)) {
    @TempValue
    KeyValuePairList.Remove("Key01");
}
else {
    @:Value0001
}
   
Comments
jaket-cp 5-Aug-16 10:04am
   
thanks - i feel like a dunce :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900