Hi sureshMGR,
Add an interface and define your methods.
Then create a public class in it and inherit the interface in this class to implement all the methods.
Then write your common code as per the return type of the method.
Interface
public interface IDataAccess
{
string GetName(string name);
DateTime GetDate();
}
public class DataAccess : IDataAccess
{
public string GetName(string name)
{
return name;
}
public DateTime GetDate()
{
return DateTime.Now;
}
}
For reusing the code in any controller inject the interface in the controller.
HomeController
public class HomeController : Controller
{
private readonly IDataAccess _dataAccess;
public HomeController() : this(new DataAccess())
{
}
public HomeController(IDataAccess dataAccess)
{
_dataAccess = dataAccess;
}
public ActionResult Index()
{
ViewBag.Name = _dataAccess.GetName("Dharmendra");
ViewBag.Date = _dataAccess.GetDate();
return View();
}
}
DetailController
public class DetailController : Controller
{
private readonly IDataAccess _dataAccess;
public DetailController() : this(new DataAccess())
{
}
public DetailController(IDataAccess dataAccess)
{
_dataAccess = dataAccess;
}
public ActionResult Index()
{
ViewBag.Name = _dataAccess.GetName("Mudassar");
ViewBag.Date = _dataAccess.GetDate();
return View();
}
}
View
Home > Index
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.Name
<br />
@ViewBag.Date
</div>
<br />
@Html.ActionLink("Go to Details", "Index", "Detail")
</body>
</html>
Detail > Index
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
@ViewBag.Name
<br />
@ViewBag.Date
</div>
<br />
@Html.ActionLink("Go to Home", "Index", "Home")
</body>
</html>
Screenshot