Tilak
Tilak

Reputation: 30728

Passing literal string from MVC view to view model

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

  1. Escape with double quote. Example -> ""key""
  2. Escape with Forward slash . Example -> \"key\"
  3. Without quotes. Example -> key
  4. Created const in model -> Example. Model.Key (Error -> instance is required)
  5. Escape with " -> Still some error

Following has worked, but looks ugly
1. Created readonly (not static) in Model.

I am looking for one of the following solutions

  1. Some escape code in html
  2. Pass Enum value in html (like Category.Key)
  3. Pass const value in html (like Constants.Key)
  4. Pass static value in html (like Model.Key)

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

Answers (2)

mlorbetske
mlorbetske

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

Adam Maras
Adam Maras

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

Related Questions