Why is T4MVC trying to start controller actions from Html.ActionLink?

In my controllers, I pass an IUnitOfWork object (which is generated from IoC), which is then used in the controller actions for database functionality ( IUnitOfWork is passed to my service level).

In one of my views, I want to give a link to /Company/View/<id> , so I call the following:

 <li>@Html.ActionLink(company.Name, MVC.Company.View(company.Id))</li> 

This is not called from the Company controller, but from a view in another controller. The problem seems to be that MVC.Company.View(company.Id) apparently calls the CompanyController.View(id) method. This is bad for two reasons.

1) Since the CompanyController constructor is never called without specifying parameters, no UnitOfWork exists, and therefore, when the View(int id) action is called, calls to the action database fail with a NullReferenceException .

2) Even if IUnitOfWork exists, my view should not trigger database calls just so that my links are generated. Html.ActionLink(company.Name, "View", new { id = company.Id }) does not call database calls (since the action method is not called), since I am not interested in tml.ActionLink(company.Name, MVC.Company.View(company.Id)) do not start any DB calls. This excessive database requires absolutely no gain.

Is there a reason T4MVC was created to work this way?


Edit: Here are the ads for 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; } } 
+4
source share
1 answer

Strange, I cannot reproduce this problem with the code above. What should happen is that a call to MVC.Company.View (company.Id) ends with a call to override your action method and never calls your real action method.

To make this work, the generated code should look like this (only saving the appropriate 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 that you see if it is different? Start by executing “Go To Definition” on “MVC”, which will open T4MVC.cs (under T4MVC.tt).

+2
source

Source: https://habr.com/ru/post/1344720/


All Articles