How can I get the url on behalf of the route in C # using asp.net mvc and razor pattern mechanism?

I am trying to get the URL of a known route name inside a razor template.

Here is my partial view

@model ScripterEngine.ViewModels.CampaignViewModel

<script type="text/javascript">

    function logTime(stage, status, async){

        var target = "@UrlHelper.RouteUrl("timetracker.clockin")";

        var postData =
        {
            'campaign_id': @Model.id,
            'agent_id': is_system_agentid.value,
            'log_id': is_attr_calldata.tracker_id,
            'stage_name': stage
        };

        if( status == 'out'){
            target = "@UrlHelper.RouteUrl("timetracker.clockout")";
        }

        if( async !== false){
            async = true;
        }

        $.ajax({
            type: 'POST',
            url: target,
            data: postData,
            async: async,
            dataType: "json",
            error: function( jqXHR, textStatus, errorThrown ){

                alert('clock ' + status + ' failed!' + jqXHR.status );
            },
            success: function(data){

                if(data && data.id && status != 'out'){
                    is_attr_calldata.tracker_id  = data.id;
                }

            }
        });
    }

</script>   

Here is my route mapping

        //Timetracker - ClockIn
        routes.MapRoute(
            "timetracker.clockin",
            "timetracker/clockin",
            new { controller = "TimeTracker", action = "ClockIn" }
        );

        //Timetracker - ClockOut
        routes.MapRoute(
            "timetracker.clockout",
            "timetracker/clockout",
            new { controller = "TimeTracker", action = "ClockOut" }
        );

However, I get a compilation error after starting the program and navigating to the route.

Compilation Error Description: An error occurred while compiling the resource required to service this request. Please review the following specific error information and change the source code accordingly.

Compiler Error Message: CS0120: An object reference is required for a non-static field, method or property 'System.Web.Mvc.UrlHelper.RouteUrl (string)'

Error point on this line

var target = "@UrlHelper.RouteUrl("timetracker.clockin")";

How can I get Url correctly from the transmission route name?

+4
1

UrlHelper @Url - WebViewPage :

public UrlHelper Url { get; set; }

Try:

var target = '@Url.RouteUrl("timetracker.clockin")';
+3

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


All Articles