简体   繁体   中英

MVC Asp.Net: Dynamic Variables and Extension Methods in Razor Views

I want to print a link in my razor view with the item's id encoded. So i've made an extension method to encode an int to a base64 string.

The code is the next:

@Html.ActionLink("Delete Item", "Delete", new{ idItem = item.IdItem.EncodeTo64() })

The item.IdItem is an int, but as i am working with dynamic variables, the EncodeTo64() method is not recognized as an extension method of the int variable. And it returns an error:

'int' doesn't have a definition for 'EncodeTo64'

So, i've found a solution: cast the dynamic variable, like this:

@Html.ActionLink("Delete Item", "Delete", new{ idItem = ((int)item.IdItem).EncodeTo64() })

It works, but i don't like this solution... do you know any way for avoiding this cast and make it work?

Thanks!

EDIT:

This is the extension method:

public static string EncodeTo64(this int number)
{
    byte[] encoded = System.Text.Encoding.UTF8.GetBytes(number.ToString());
    return Convert.ToBase64String(encoded);
}

This can't be done with a dynamic type because the compiler will never be able to infer which extension method to use.

Under the hood the compiler will turn this:

myVar.EncodeTo64();

Into this:

MyStaticClass.EncodeTo64(myVar);

It has to have this information at compile time, but because you are using a dynamic , you are explicitly telling the compiler to wait until runtime to work out which call to make.

You have three options:

  1. Use a strongly typed model
  2. Add a property/method that does it for you
  3. Live with the cast

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM