TheRiddler
TheRiddler

Reputation: 169

Using Url Helpers with Web Forms

I have got a webforms application I have added an MVC Area to it and within there I have a Controller called MyController.

I need to do something like the below in the master page of the web forms application. This is copied from another web app I have which is all MVC 5.

So in my Layout page on that App I have:

<script type="text/javascript">
    // assign values used in core js file
    returnUrl = '@Url.Action("MyAction", "My", new { returnUrl = @Request.Url.AbsoluteUri })';
    anotherUrl = '@Url.Action("MyAction2", "My")';
</script> 

In my core js file return url is used in a ajax call like so:

 $.ajax({
            url: returnUrl, // return url gets set form _Layout.cshtml
            type: 'GET',
            success: function (data) {
                alert("yay");
            },
            error: function (xhr) {
                alert("failed");
            }
        });

Is there anyway I can use the same functionality in WebForms to generate the Urls to go to MyController for these ajax urls.

I have came across this answer - is the accepted answer the correct way of doing this?

Upvotes: 0

Views: 1468

Answers (1)

Stilgar
Stilgar

Reputation: 23561

Yes the accepted answer you linked is the correct answer except... Please don't add all this code in your markup. Put it in the code behind and expose properties with the URLs

In your code behind put:

public string ReturnUrl
{
   get
   {
       return urlHelper.RouteUrl("MyAction", "My", new { returnUrl = Request.Url.AbsoluteUri });
   }
}

You should also add a field called urlHelper of type System.Web.Mvc.UrlHelper and add this code to the Page_Init event

var requestContext = new System.Web.Routing.RequestContext(
       new HttpContextWrapper(HttpContext.Current),
       new System.Web.Routing.RouteData());
urlHelper = new System.Web.Mvc.UrlHelper(requestContext);

In your form put just

<script type="text/javascript">
    // assign values used in core js file
    returnUrl = <%= ReturnUrl %>
</script> 

Upvotes: 1

Related Questions