Reputation: 30728
I have to pass literal string to the Model from the view.
Model has a Dictionary<string,string>
and i need to pass key from the view.
<a href="@Url.Content("~/temp/Data/" + Model.Dict[<Need to pass key here ???>])"
I have tried following but could not succeed
Following has worked, but looks ugly
1. Created readonly (not static) in Model.
I am looking for one of the following solutions
Any one is fine, but specifying multiple/all in answer is welcomed.
Previously, there was array in place of dictionary, and passing index was working perfect.
<a href="@Url.Content("~/temp/Data/" + Model.Dict[0])"
I am a newbie to MVC. The question may be basic but I have given up.
Upvotes: 0
Views: 1554
Reputation: 5659
How about creating a variable to hold the string in a Razor code block and passing it in to the dictionary?
@{
//Set the value of the key to a temporary variable
var theKey = "key";
}
<!-- Reference the temporary variable in the indexer -->
<a href="@Url.Content("~/temp/Data/" + Model.Dict[theKey])"></a>
To use a const (or any static from your model), you'll have to use the type qualified name of the field/property, just like in code.
So if you've got
public const string Foo = "Bar";
or
public static readonly Foo = "Bar";
in
public class ThePageModel
{
...
}
Your code in the view would look more like
<a href="@Url.Content("~/temp/Data/" + Model.Dict[MyApplication1.Models.ThePageModel.Foo])"></a>
Same goes for enums, though since your dictionary accepts a string and not whatever the enum type is, to make this example hang together there'll be a .ToString()
after accessing the enum in the view.
public enum MyEnum
{
MyDictionaryKey1,
MyDictionaryKey2,
MyDictionaryKey3
}
...
<a href="@Url.Content("~/temp/Data/" + Model.Dict[MyApplication1.Models.MyEnum.MyDictionaryKey1.ToString()])"></a>
Upvotes: 2
Reputation: 26883
You don't need to do anything fancy here; the Razor view engine knows how to handle strings.
<a href="@Url.Content("~/temp/Data/" + Model.Dict["key"])">
Upvotes: 2