In asp.net MVC, multiple controllers need to share the same view and pass their own entity classes for the view to operate on. The problem is, these entity classes are not of the same type, and the attributes in them are somewhat different. So in the case of shared views, how do views handle these entity classes?

We know that whether it’s passed through the View, or whether it’s passed through the ViewBag, in the View, we need to cast it back to the original type before we can use it. Now that the type of entity class being passed is different, it becomes difficult to convert.

Of course, it’s ok to pass in an extra type parameter, judge it in the view, and convert it separately, but it always feels a bit silly.

One option is to convert all the entity classes to JObject in the controller, and then manipulate the JObject object in the view.

No code no J8:

Controller:

using Newtonsoft.Json.Linq;

public ActionResult ControllerA(int id)
{
    EntityA objA = ... // Get the entity class A object

    return View("PublicView", JObject.FromObject(objA));
}
public ActionResult ControllerB(int id)
{
    EntityB objB = ... // Get the entity class B object

    return View("PublicView", JObject.FromObject(objB));
}
Copy the code

\

View: \

@model Newtonsoft.Json.Linq.JObject

@using Newtonsoft.Json.Linq;

@{
    Layout = null;


    int id = Model.Value<int> ("ID");
    string owner = Model.Value<string> ("Owner");
    stringcreateTime = Model.Value<DateTime? > ("CreateTime").ToString() ?? "";
}
Copy the code

\

This approach, in addition to the MVC framework, is also suitable for interface programming with the same method content but different return value types. \