Search code examples
asp.net-mvcasp.net-mvc-views

How can you get the current View's Model name?


I would expect this to be asked/answered a hundred times, but the only answer I can find anywhere on the entire Internet is:

var currentModel = Model.GetType().Name;

This almost works but for example if the Model is defined as

@model Myproject.Model.User_info

Then the value of currentModel ends up as something like this:

User_info_23L7HGAFWLIUHI7GLIUBGFWAKHGI73I37GArwq

Do I really have to strip off everything starting with the penultimate underscore? Or is there a better way?


Solution

  • Per Jasen's comment on the question above, the answer I ultimately went with was this:

    var currentModel = System.Data.Entity.Core.Objects.ObjectContext.GetObjectType(Model.GetType()).Name;
    

    ... this reliably produces the correct name of both models and viewmodels as they are defined by the developer.