2

I have to call a method which is implemented in a class. Is it possible from razor view?

Note: I dont want to expose the class directly to view

ekad
  • 14,436
  • 26
  • 44
  • 46
User4179525
  • 516
  • 1
  • 4
  • 18

1 Answers1

1

Yes, you can bind your Razor model to an interface (although you'll have to inject a concrete instance somewhere, typically your controller).

public ActionResult Index()
{
    IList<string> list = new List<string> {"one", "two"};
    return View(list);
}

Razor view:

@model IList<string>
@{ Model.RemoveAt(0); }

In this simple test case, RemoveAt() is guaranteed by the IList<T> interface, meaning that the underlying concrete implementation has not been exposed to the view.

An additional example would be a custom implementation where one public method of a concrete class is guaranteed by an interface and another is not:

public class Test : ITest
{
    public int Id { get; set; }
    public string Name { get; set; }

    public string GetName()
    {
        return Name;
    }

    public int GetId()
    {
        return Id;
    }
}

public interface ITest
{
    string GetName();
}

Controller:

public ActionResult Index()
{
    var test = new Test() {Id = 1, Name = "Test"};
    return View(test);
}

Razor View:

@model ITest
@(Model.GetId())

In this case GetId() would be highlighted red in the Razor view as invalid syntax and you would receive the following compilation error at runtime.

ITest' does not contain a definition for 'GetId'

On the flipside, Model.GetName() would correctly output "Test".

David L
  • 32,885
  • 8
  • 62
  • 93
  • Is there a way that i can create an instance in global.asax instead of creating in controller? because am going to use the method in Layout. Thanks!! – User4179525 May 28 '15 at 21:42
  • That's a good deal more complicated (and is honestly a separate question). Your best bet is something like this: http://stackoverflow.com/questions/5453327/how-to-set-viewbag-properties-for-all-views-without-using-a-base-class-for-contr – David L May 28 '15 at 21:47