1

On one MVC 4 project, we have a lot of Pages.cshtml that receive a collection of Models (generally hundreds of rows), which we serialize as JSON via

@Html.Raw(Json.Encode(Model));

The problem is that on some of those pages we are receiving an exception (The length of the string exceeds the value set on the maxJsonLength).

We know what is the reason and how to fix it. The thing is that I would like to create a similar Json.Encode() method (using Json.Net), so we do not need to modify all the cshtml pages. If I create a Json.Encode() method, Razor complains about ambiguous reference between My.Namespace.Json and System.Web.Helpers.Json.

Again, we know how to solve this by adding an alias on the page:

@using Json = My.Alias.Json

What I'm trying to do is to transparently instruct Razor to choose this alias for all the cshtml pages that uses this Json.Encode. The reason is that I want this to be transparent, so later if somebody adds a new page, automatically he will start to use our custom JSON implementation.

I think on Views/Web.config you can add namespaces and some configurations for Razor, but I don't see how to explicitly set the aliases.

jparaya
  • 1,331
  • 11
  • 15

1 Answers1

1

Interesting issue, but as far as I know that's not possible. See e.g. this: C#: Globally alias a generic class name?

As an alternative you could create a helper method Html.JsonEncode() and teach, drill or entice everyone to use that.

If you make it also do the Raw() call and return IHtmlString, then you can do @Html.JsonEncode(Model) as opposed to @Html.Raw(Html.JsonEncode(Model)) and before you know it everybody is a fan of your new method.

Community
  • 1
  • 1
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • Yes, you're right. Unfortunately, my approach created some issues with cached assemblies... not sure why. Anyway, I applied your approach. Thanks for the tip! – jparaya Feb 08 '17 at 12:18