0
votes

In my DOT NET CORE MVC application i am using Url Action inside a view to generate and redirect action link

@Url.Action ("Action Name","Controller Name")

Above synatax is working fine for me where i am passing static value of controller like

'@Url.Action(nameof(EmployeeController.Edit),"Employee")'

Here controller name is static and i want to avoid a situation like in future if i change controller name at that time i need to remember this changes in view so my requirement is Basically i want to pass controller name like below

'@Url.Action(nameof(EmployeeController.Edit),nameof(EmployeeController))'

Controller and Action method is

public class EmployeeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Edit()
        {
            return RedirectToAction("Index", "HotelList", new { area = "Hotel" });
        }
    }

Suggest me best way to do this

Thanks in advance

1

1 Answers

1
votes

By convention controller classes end in the word Controller but references to them for URL purposes do not. (Honestly this discrepency has never even occurred to me until now.) It's probably best not to mess with that convention, as it could cascade into other problems. Instead, maybe just modify the string being used in the result.

Something like this:

nameof(EmployeeController).Replace("Controller", string.Empty)

If this is used a lot, perhaps encapsulate it into a helper or extension method somewhere for simplicity.