Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Url.Action() in a class file?

How can I use Url.Action() in a class file of MVC project?

Like:

namespace _3harf {     public class myFunction     {         public static void CheckUserAdminPanelPermissionToAccess()         {             if (ReferenceEquals(HttpContext.Current.Session["Loged"], "true") &&                 myFunction.GetPermission.AdminPermissionToLoginAdminPanel(                     Convert.ToInt32(HttpContext.Current.Session["UID"])))             {                 HttpContext.Current.Response.Redirect(Url.Action("MainPage", "Index"));             }         }     } } 
like image 428
Erçin Dedeoğlu Avatar asked Jan 01 '14 13:01

Erçin Dedeoğlu


People also ask

What does URL action do?

A URL action is a hyperlink that points to a web page, file, or other web-based resource outside of Tableau. You can use URL actions to create an email or link to additional information about your data. To customize links based on your data, you can automatically enter field values as parameters in URLs.

What is the difference between URL action () and HTML action ()?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.


2 Answers

You will need to manually create the UrlHelper class and pass the appropriate RequestContext. It could be done with something like:

var requestContext = HttpContext.Current.Request.RequestContext; new UrlHelper(requestContext).Action("Index", "MainPage"); 

However, you are trying to achieve redirection based on authentication. I suggest you look at implementing a custom AuthorizeAttribute filter to achieve this kind of behavior to be more in line with the framework

like image 82
Simon Belanger Avatar answered Oct 07 '22 20:10

Simon Belanger


Pass the RequestContext to your custom class from the controller. I would add a Constructor to your custom class to handle this.

using System.Web.Mvc; public class MyCustomClass {     private UrlHelper _urlHelper;     public MyCustomClass(UrlHelper urlHelper)     {         _urlHelper = urlHelper;     }     public string GetThatURL()     {                string url=_urlHelper.Action("Index", "Invoices");        //do something with url or return it       return url;     } } 

You need to import System.Web.Mvc namespace to this class to use the UrlHelper class.

Now in your controller, create an object of MyCustomClass and pass the controller context in the constructor,

UrlHelper uHelp = new UrlHelper(this.ControllerContext.RequestContext); var myCustom= new MyCustomClass(uHelp );     //Now call the method to get the Paging markup. string thatUrl= myCustom.GetThatURL(); 
like image 45
Shyju Avatar answered Oct 07 '22 20:10

Shyju