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
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
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".