Home > Back-end >  Indicate to ReSharper or Visual Studio that JSON variable is instance of Model
Indicate to ReSharper or Visual Studio that JSON variable is instance of Model

Time:04-28

My front-end libraries sometimes require JSON data from my MVC application (e.g. jQGrid). I'm accommodating this when needed by converting the required model classes to JSON. However I'm running into an issue where refactoring such models can occasionally become difficult; neither ReSharper, nor Visual Studio, can identify this "model access" after the model's been converted into JSON-- only when it's used within C# templating (either old-school WebForms or Razor).

Is there any way I can hint to either VS or ReSharper that, for instance, the JS variable rowObject used within jQGrid is equivalent to a usage of the C# class MyModel? Ideally so I can get things like intellisense, but more importantly, so that ReSharper's "Find Usages" of the class / its properties can identify that it's being used here. (e.g. "Find Usages" of MyModel.Name => this usage of rowObject.Name)

// <Back-End>
public JsonResult JsonList(string userName)
{
    var model = new List<MyModel>()
    ...
    return Json(model.OrderByDescending(x => x.WhenSent), JsonRequestBehavior.AllowGet);
}

// <Front-End>
$("#jQGridExample").jqGrid({
    url: '<%= Url.Action("JsonList", "MyController") %>',
    datatype: "json",
    ...
    formatter: function (cellvalue, options, rowObject) {
    // rowObject is of type "MyModel" but neither tool will know this.
    // If I remove a property from "MyModel" without updating the JS & rowObject uses it,
    // this can become an easily missed front-end regression.
    }

CodePudding user response:

No, because there is not only a layer-wise break (front vs. back end), but a technical one as well - namely JS vs. C#. As long as there is no direct bridge between C# and JS on a compiler/R# level, this will remain impossible.

Of course you can mitigate those issues by creating models in JS/TypeScript that are similar to their C# pendants (meaning same names, properties, etc.) - e. g. here and here. But they are not technically the same.

  • Related