sandeep singh
sandeep singh

Reputation: 143

use variable for controller and action in @url.action

Anyone know how can i use varibale in '@Url.Action(action, controller)?EmpId=' + EmpId + '&SubModuleId=' + SubModuleId;

 $('.CreateEditView').click(function () {
            addloader();
            var view = $(this).attr("data-view");
            var action = $(this).attr("data-action");
            var container = $(this).attr("data-container");
            var controller = $(this).attr("data-container");
            var view = $(this).attr("data-container");
            var EmpId = $("#EmployeeId").val();
            var SubModuleId = $("#SubModuleId").val();
            var url = '@Url.Action(action, controller)?EmpId=' + EmpId + '&SubModuleId=' + SubModuleId;
            //var url = '@Url.Action("'"+action+"'", "'"+controller+"'")?EmpId=' + EmpId + '&SubModuleId=' + SubModuleId;
                             ***// action and controller doesn't exist error***
            $('#' + view + '').html("");
            $('#' + view + '').load(url);
            removeloader();
            $("#" + container + " .sucessmsg").addClass("hide");
        });

Upvotes: 0

Views: 2223

Answers (1)

user3559349
user3559349

Reputation:

action and controller are javascript variables while @Url.Action() is razor code that is parsed on the server before its sent to the view. Those variables don't yet exist (are not in scope) so you get an error.

One option would be to use

var url = '/' + controller + '/' + action + '?EmpId=' + EmpId + '&SubModuleId=' + SubModuleId;

however a better solution would be to render one data-val attribute in your elements with class="CreateEditView" - say data-url="@Url.Action("yourAction", "yourController")" and then access it using var url = $(this).data('url');

Side note. In your .load() method your could also use it as

$('#' + view + '').load($(this).data('url'), { EmpId: EmpId, SubModuleId: SubModuleId });

Note however this usage (adding the parameters as an object) will mean that the .load() function will make a POST rather than a GET

Upvotes: 2

Related Questions