Why does T4MVC try to run controller actions from Html.ActionLink? - asp.net-mvc

In my controllers I pass in a IUnitOfWork object (which is generated from IoC) which is then used in controller actions for database functionality (the IUnitOfWork is passed to my service layer).
In one of my views, I want to give a link to the /Company/View/<id>, so I call the following:
<li>#Html.ActionLink(company.Name, MVC.Company.View(company.Id))</li>
This is being called not from the Company controller, but from a view in a different controller. The problem seems to be that the MVC.Company.View(company.Id) seems to actually be invoking the CompanyController.View(id) method itself. This is bad for 2 reasons.
1) Since the CompanyController's non-parameterless constructor is never called, no UnitOfWork exists, and thus when the View(int id) action is called, the action's database calls fail with a NullReferenceException.
2) Even if IUnitOfWork exists, my view should not be triggering database calls just so my links are generated. Html.ActionLink(company.Name, "View", new { id = company.Id }) doesn't trigger any database calls (as the action method isn't invoked) so as far as I'm concerned tml.ActionLink(company.Name, MVC.Company.View(company.Id)) shouldn't be triggering any DB calls either. It's excessive database calls for absolutely no gain.
Is there any reason T4MVC was created to function this way?
Edit: Here are the declarations for the CompanyController
public partial class CompanyController : MyCustomBaseController
{
public CompanyController(IUnitOfWork unitOfWork)
{
}
public virtual ActionResult Add(int jobSearchId)
{
}
public virtual ActionResult Edit(int id)
{
}
[HttpPost]
public virtual ActionResult Edit(Company company, int jobSearchId)
{
}
public virtual ActionResult View(int id)
{
}
}
public class MyCustomBaseController: Controller
{
public MyCustomBaseController()
{
}
public int CurrentUserId { get; set; }
}

Strange, I'm not able to repro this issue with the code above. What should be happening is that calling MVC.Company.View(company.Id) ends up calling an override of your action method, and never actually call your real action method.
To make this work, the generated code should look like this (only keeping relevant things):
public static class MVC {
public static Mvc3Application.Controllers.CompanyController Company = new Mvc3Application.Controllers.T4MVC_CompanyController();
}
public class T4MVC_CompanyController: Mvc3Application.Controllers.CompanyController {
public T4MVC_CompanyController() : base(Dummy.Instance) { }
public override System.Web.Mvc.ActionResult View(int id) {
var callInfo = new T4MVC_ActionResult(Area, Name, ActionNames.View);
callInfo.RouteValueDictionary.Add("id", id);
return callInfo;
}
}
Can you look at the generated code you get to see if it's any different? Start by doing a 'Go To Definition' on 'MVC', which will open up T4MVC.cs (under T4MVC.tt).

Related

Return a View from external Class

I want to choose between multiple clients before returning a view in ASP.NET Core MVC.
So let there be a HomeController with the following code:
public class HomeController : Controller
{
public virtual IActionResult Index()
{
return View();
}
}
Now I have multiple clients, and I want to decide what view will be returned. But not at this place, so I want to write it in another file.
So my question is, is there something possible like this:
public class HomeController : Controller
{
public virtual IActionResult Index()
{
ViewChooser vc = new ViewChooser();
return vc.GetNextView();
}
}
public class ViewChooser
{
public IActionResult GetNextView()
{
// do some stuff and then..
return View("aaaa");
}
}
The class "ViewChooser" does not inherit from Controller, so I can't just write return View().
The reason why I want this to work like this is because I want to choose between multiple workflows without changing the URL. (Otherwise areas would be a possible solution for my problem.)
So if customer A calls www.myserver.com/function1 he get another functionality and view as customer B.
Any ideas? Or am I far away from the solution?
Regards
One option would be to have ViewChooser inherit from Controller. It is, after all, trying to return a view which is something a controller does.
Alternatively, just have ViewChooser return the name of the view:
public class ViewChooser
{
public string GetNextView()
{
// do some stuff and then..
return "aaaa";
}
}
And your controller can use that for its view selection:
public class HomeController : Controller
{
public virtual IActionResult Index()
{
ViewChooser vc = new ViewChooser();
return View(vc.GetNextView());
}
}
This would mean that GetNextView() must always return a valid named view, never another kind of IActionResult. But would decouple the ViewChooser from the MVC framework.
If you have fixed number of clients say "5 clients" then you can create 5 different ActionResult Methods which will return 5 different views. Afterwards you can create a custom attribute where you will write the logic for fetching the client information. You can put this custom attribute over each ActionResult method.

Inheriting from controller, overriding save method with different type

I have a project that has a 'core' version, and a 'customised' version.
They are separate projects.
'customised' inherits functionality from 'core' and in some case overrides methods.
For example:
I have a user model that looks like this:
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Then, in a separate assembly,
public class User : Core.User
{
public string CustomProperty { get; set; }
}
I then have a controller (in my 'core' assembly)
public class UserController : Controller
{
[HttpPost]
public ActionResult SaveUser(User user)
{
}
}
In my other project, I have a UserController that inherits from Core.UserController:
public class UserController : Core.UserController
{
[HttpPost]
public ActionResult SaveUser(Custom.User user)
{
}
}
Obviously, in my Global.asax I have the controller namespaces mapped
However, when I hit the SaveUser method, I get
The current request for action SaveUser on controller type
UserController is ambiguous between the following action methods
While I understand the problem, is there any way around this?
In a nutshell:
I want to use Core.UserController methods most of the time, but in this instance, I need to use my Custom.UserController SaveUser method (since it takes my Custom.User type)
Polymorphism?
public class UserController : Controller
{
[HttpPost]
public virtual ActionResult SaveUser(User user)
{
}
}
public class UserController : Core.UserController
{
[HttpPost]
public override ActionResult SaveUser(User user)
{
var customUser = user as Custom.User;
if(customUser != null)
{
//Your code here ...
}
}
}
Another possible workaround if the polymorphism solution doesn't work or isn't acceptable, would be to either rename your UserController or its action method to something slightly different:
public class CustomUserController : Core.UserController
{
[HttpPost]
public ActionResult SaveUser(Custom.User user)
{
}
}
public class UserController : Core.UserController
{
[HttpPost]
public ActionResult SaveCustomUser(Custom.User user)
{
}
}
If you wanted to keep the routes consistent with the other project, you would just have to create a custom route for this.
I encountered the same problem in my own project today and came across your post.
In my case, while I didn't want to alter the way the core controller's logic functioned, I was able to make changes to its code, and thus its modifier keywords. After adding virtual to the base controller's actions, and override to my derived controller's actions. The original controller's actions still function, my derived controller uses my customized actions, no more ambiguous errors.
I realize you may not be able to modify your Core controller, and if this is the case, then you need to differentiate your actions using some other means. Action name, parameters or some other solution such as a custom implementation of ActionMethodSelectorAttribute. That was my first attempt at this problem, but before I got too far down that path of how to implement it, I discovered the virtual/override solution. So I don't have code to share on that route unfortunately.

Accessing Service Layer from Controller in MVC Project

I previously had a controller that had code like this:
public ActionResult Method(int Id)
{
var foo = doThis(Id)
return View("Error");
}
doThis() is a method that exists in the controller, and performs some logic. I'm now trying to relocate all business logic to a Services project that contains a bunch of classes.
To start I added a class library Project.Services and then added a class FooServices which contains the following:
namespace Project.Services
{
class FooServices
{
public List<Bar> doThis(int Id)
{
//Do stuff
return parentSets;
}
}
}
I've added a reference to this project from my MVC project, and a reference from this Services project to my data model project, but I'm not sure how to proceed now. How can I access these methods from controllers?
How can I access these methods from controllers?
In order to access an instance method you need an instance of the object:
public ActionResult Method(int Id)
{
var foo = new FooServices().doThis(Id)
return View("Error");
}
Of course by doing this you are now strongly coupling your controller logic with a specific implementation of your service making it very difficult to unit test your controllers in isolation.
So to weaken the coupling start by introducing an abstraction:
public interface IFooServices
{
List<Bar> DoThis(int id)
}
and then have your service layer implement this interface:
public class FooServices: IFooServices
{
public List<Bar> DoThis(int id)
{
//Do stuff
return parentSets;
}
}
Alright, now your controller could work with this abstraction:
public class HomeController: Controller
{
private readonly IFooServices service;
public HomeController(IFooServices service)
{
this.sevrice = service;
}
public ActionResult Method(int id)
{
var foo = this.service.DoThis(id)
return View("Error");
}
}
Great, at this stage we really have a weak coupling between your controller and the service layer. All that's left now is to configure your favorite dependency Injection framework to inject the specific service into your controller.

I want to use session in the asp.net mvc controller constructor

I'm new to Mvc.
Sorry to my english. ^^
I have some question about asp.net MVC session in the controller.
The Scenario things that I want to do is like follows..
First of all, My development circumstance is entityframework and mvc3.
When Someone logged in each one has different database. So, Each has connect different database.
So, Each person has his own session value which is database connection string. So far so good.
I have simple database Repository and at the each repository's constructor can change database connection.
At controller which calls Repository class, I need session value. But As I know Controller's construction can't keep session value. right?
I want your good advice. Thanks in advance.
Code samples are below:
public class MasterRepository
{
DBEntities _db;
public MasterRepository(string con)
{
_db = new DBEntities(con);
}
}
public class TestController : Controller
{
private string con;
MasterRepository _db;
public TestController()
{
_db = new MasterRepository(Session["conn"].ToString()); // Session is null I want to solve this Part...
}
public ActionResult Index()
{
string con = Session["conn"].ToString(); // Session is assigned.
return View();
}
}
These should explain what's happening to cause Session to be null, and give you a few possible solution options:
Is ASP.NET MVC Session available at any point durign controller construction
Why my session variables are not available at construction of a Controller?
Session null in ASP.Net MVC Controller Constructors
I think you have missed out the "service" part of the controller - service - repository pattern:
http://weblogs.asp.net/fredriknormen/archive/2008/04/24/what-purpose-does-the-repository-pattern-have.aspx
But when you go down this path you will probably also need to learn IoC as well.
Then your code would look more like:
public class MasterRepository
{
public Foo GetAllFoo()
{
return ObjectContextManager.GetObjectContext().AsQueryable().ToList();
}
}
public class MasterService
{
MasterRepository _repository;
public MasterService(MasterRepository repository) // use IoC
{
_repository = repository;
}
public Foo GetAllFoo()
{
return _repository.GetAllFoo();
}
}
public class TestController : Controller
{
MasterService _service;
public TestController(MasterService service) // use IoC
{
_service = service;
}
public ActionResult Index()
{
var model _service.GetAllFoo();
return View(model);
}
}

Bestpractice DI with ASP.NET MVC and StructureMap - How to inject dependencies in an ActionResult

I edited my whole question, so do not wonder :)
Well, I want to have an ActionResult that takes domain model data and some additional parameters, i.e page index and page size for paging a list. It decide itself if it returns a PartialViewResult or a ViewResult depending on the kind of web request (ajax request or not).
The reffered data shall be mapped automatically by using an IMappingService, which is responsible for transforming any domain model data into a view model.
The MappingService uses AutoMapper for simplicity.
MappingActionResult:
public abstract class MappingActionResult : ActionResult
{
public static IMappingService MappingService;
}
BaseHybridViewResult:
public abstract class BaseHybridViewResult : MappingActionResult
{
public const string defaultViewName = "Grid";
public string ViewNameForAjaxRequest { get; set; }
public object ViewModel { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null) throw new ArgumentNullException("context");
var usePartial = ShouldUsePartial(context);
ActionResult res = GetInnerViewResult(usePartial);
res.ExecuteResult(context);
}
private ActionResult GetInnerViewResult(bool usePartial)
{
ViewDataDictionary viewDataDictionary = new ViewDataDictionary(ViewModel);
if (String.IsNullOrEmpty(ViewNameForAjaxRequest))
{
ViewNameForAjaxRequest = defaultViewName;
}
if (usePartial)
{
return new PartialViewResult { ViewData = viewDataDictionary, ViewName = ViewNameForAjaxRequest };
}
return new ViewResult { ViewData = viewDataDictionary };
}
private static bool ShouldUsePartial(ControllerContext context)
{
return context.HttpContext.Request.IsAjaxRequest();
}
}
AutoMappedHybridViewResult:
public class AutoMappedHybridViewResult<TSourceElement, TDestinationElement> : BaseHybridViewResult
{
public AutoMappedHybridViewResult(PagedList<TSourceElement> pagedList)
{
ViewModel = MappingService.MapToViewModelPagedList<TSourceElement, TDestinationElement>(pagedList);
}
public AutoMappedHybridViewResult(PagedList<TSourceElement> pagedList, string viewNameForAjaxRequest)
{
ViewNameForAjaxRequest = viewNameForAjaxRequest;
ViewModel = MappingService.MapToViewModelPagedList<TSourceElement, TDestinationElement>(pagedList);
}
public AutoMappedHybridViewResult(TSourceElement model)
{
ViewModel = MappingService.Map<TSourceElement, TDestinationElement>(model);
}
public AutoMappedHybridViewResult(TSourceElement model, string viewNameForAjaxRequest)
{
ViewNameForAjaxRequest = viewNameForAjaxRequest;
ViewModel = MappingService.Map<TSourceElement, TDestinationElement>(model);
}
}
Usage in controller:
public ActionResult Index(int page = 1)
{
return new AutoMappedHybridViewResult<TeamEmployee, TeamEmployeeForm>(_teamEmployeeRepository.GetPagedEmployees(page, PageSize));
}
So as you can see the IMappingService is hidden. The controller should not know anything about the IMappingService interface, when AutoMappedHybridViewResult is used.
Is the MappingActionResult with the static IMappingServer appropriate or am I violating the DI principle?
I think a better design is to have a ViewResultFactory that depends on IMappingService, then you can inject that into your controller. Then you call it like so:
public class MyController : Controller
{
IViewResultFactory _viewResultFactory;
ITeamEmployeeRepository _teamEmployeeRepository;
public MyController(IViewResultFactory viewResultFactory)
{
_viewResultFactory = viewResultFactory;
}
public ActionResult MyAction(int page, int pageSize)
{
return
_viewResultFactory.GetResult<TeamEmployee, TeamEmployeeForm>(
_teamEmployeeRepository.GetPagedEmployees(page, pageSize));
}
}
The implementation would like this (you would need to create overloads for each of your HybridViewResult constructors):
public HybridViewResult<TSourceElement, TDestinationElement> GetResult<TSourceElement, TDestinationElement>(PagedList<TSourceElement> pagedList)
{
return new HybridViewResult<TSourceElement, TDestinationElement>(_mappingService, pagedList);
}
That way you hide the implementation from your controllers, and you don't have to depend on the container.
There are a few different points that you could inject IMappingService. http://codeclimber.net.nz/archive/2009/04/08/13-asp.net-mvc-extensibility-points-you-have-to-know.aspx is a good site for help in picking the appropriate extensibility points for .NET MVC.
If you want to stick with having this functionality be a derived ActionResult, then I think you could put the dependency in the ActionInvoker if you want to, but the Controller makes more sense to me. If you don't want the IMappingService in the Controller, you could always wrap it in a HybridViewResultFactory, and access that object in the Controller. In that case your shortcut methods would look like:
public HybridViewResult<TSourceElement, TDestinationElement> AutoMappedHybridView<TSourceElement,TDestinationElement>(PagedList<TSourceElement> pagedList, string viewNameForAjaxRequest)
{
HybridViewResultFactory.Create<TSourceElement, TDestinationElement>(pagedList, viewNameForAjaxRequest);
}
etc.
I'm not sure why you need to use an ActionResult, but if there is no reason that makes it explicitly necessary, you could create a HybridViewModel class and a HybridViewModelBinder class that is injected with the mapping service dependency.
I am assuming you want to use constructor injection, but if you have the StructureMap dependency in your UI assembly, you could access a static dependency resolver class (like Clowers said).
This question would be easier to give a definite answer to if I understood why you using an ActionResult.
It seems like you are using the action result to handle two functionalities that do not necessarily go together all the time, and that could be used separately. Also, there is not a clear indication that it needs to be in an ActionResult.
Presumably, you could (a) leverage the Automapper functionality for results other than html (ViewResult) output, and (b) you could leverage the functionality of auto-detecting ajax requests without needing to automap the model.
It seems to me like the automapping of the view model could be used to inject the view model into the controller action directly, thus removing the controller's dependency on the IMappingService. What you would need is a ModelBinder class to be injected with your IMappingService (the implementation of which I assume contains a repository or datastore type dependency).
Here is a good article explaining how to leverage model binders: http://odetocode.com/blogs/scott/archive/2009/04/27/6-tips-for-asp-net-mvc-model-binding.aspx.
Then you can overwrite the DefaultModelBinder in the classes that need to be Automapped as follows:
public ActionResult DoItLikeThis([AutoMap(typeof(MyDomainModelClass))]MyViewModelClass viewModel){
//controller action logic
}
Now, regarding the HybridViewResult, I would suggest that you handle this with an Action Filter instead. So, you could just use ActionResult or ViewResultBase as the Result type of your action method and decorate it with an action filter, i.e.:
[AutoSelectViewResult]
public ViewResultBase AndDoThisLikeSo(){
//controller action logic
}
I think overall this will be a much better solution than coupling these two functionalities to an ActionResult.

Resources