Heidi T.
Heidi T.

Reputation: 75

Call Html.Actionlink from script

I am trying to call action link from script but it is not working, but when I am using window.open it is working but I need other properties because of my CSS view, if I can call Html.ActionLink I can open it in tabs at the same page with my template.

Here is code:

 function OnRowDblClick(s, e) {
    alert(e.visibleIndex);
    GridViewCitiesList.GetRowValues(e.visibleIndex, "CityGuid", OnGetRowValues);
}

function OnGetRowValues(data) {
    var url = Html.ActionLink("Edit", "CityAction", "City", new { CRUDType: CRUDTypes.Update, ModelGuid: data }, new { class: "btn btn-success", target: "_blank", title: "City Detail" });
    window.location.href = url;
}

Error says:

Uncaught ReferenceError: Html is not defined

Upvotes: 1

Views: 1079

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

You have several issues with current code:

1) Html.ActionLink is an MVC helper, you should add @ prefix in Razor CSHTML page to set it as HTML helper.

2) Html.ActionLink generates anchor tag (<a>), not URL string. Use @Url.Action() helper to create URL.

3) data is client-side variable, you can't pass it to HTML helper which processed server-side. You need to build query string to add data with ModelGuid parameter.

Based from explanations above, change URL definition from this:

// this is totally wrong
var url = Html.ActionLink("Edit", "CityAction", "City", new { CRUDType: CRUDTypes.Update, ModelGuid: data }, new { class: "btn btn-success", target: "_blank", title: "City Detail" });

to this one:

var url = '@Url.Action("CityAction", "City", new { CRUDType = CRUDTypes.Update })&ModelGuid=' + data;

Or you may try adding ModelGuid parameter query string inside routeValues and replace its value from client-side:

// this setup should also work
function OnGetRowValues(data) {
    var url = '@Url.Action("CityAction", "City", new { CRUDType = CRUDTypes.Update, ModelGuid = "XXXX" })';
    url = url.replace('XXXX', data);

    window.location.href = url;
}

Upvotes: 1

Related Questions