I have an anchor tag that with a javascript function on onclick, call my method to update page via Ajax.
The page show a detail of an order and a ajax update show a position for a detail order.
The problem is: how can i generate and pass URL dynamically?
This is my anchor tag:
<a class="nav-link text-dark text-center p-0 collapsed"
data-toggle="collapse"
data-target="#Details"
aria-expanded="true"
aria-controls="Details"
href="@Url.Page("Area/Details/" + @Model.wItem.GUID, "ShowDetails")"
id="ShowDetails"
onclick="ShowDetailsAjax(this, '@Model.wItem.GUID')">
@item.Position
</a>
And this is my javascript function:
function ShowPositionAjax(x, _GUID) {
var _url = '';
var _position = x.outerText;
var parameters = "{'position':'" + _position + "','GUID':'" + _GUID + "'}";
$.ajax({
url: _url,
type: 'GET',
cache: false,
async: true,
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: parameters
})
.done(function (result) {
$('#MainframeContents').html(result);
});
}
The razor page, where anchor tag is, named Area/Details/123456-45646-123132(where 123456-45646-123132 is GUID). The problem is, I don’t want to hardcode the url because GUID can change.
I have try with
href="@Url.Page("Area/Details/" + @Model.wItem.GUID, "ShowDetails")"
but in javascript href is null.
3
Answers
I post here the solution; it's better than in a comment.
Originally i use this href:
with Url.Page because i'm using Razor and not MVC. Reading the MS doc(https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-3.0) i notice that i'm using the areas so, the correct href should be:
Details: is the name of my Page
ShowDetails: is the name of my GET handler
Area: is the name of my Area
position and GUID: is the parameter of my GET handler
The result href URL will be like:
/en/Area/Details/45646546-1213-156416-45646-5464666?position=1&handler=ShowDetails
that call my handler:
Hope this can save time to other.
Thanks to @Rory McCrossan for hers advices.
You can use the
href
attribute to do this. You say it doesn’t work for you, yet you haven’t shown what you tried. Usingattr()
will get you the required value. You also appear to be trying to send JSON in a GET request which isn’t quite right, especially when the data you need is already in thehref
URL.Also note that you should avoid using
onclick
and other event attributes as they are outdated. As you’re using jQuery you can easily attach your event handlers unobtrusively.Finally,
async: false
is incredibly bad practice and should not be used. You don’t need it in any case as you’ve implemented thedone()
method. With all that said, try this:Maybe this would help someone but recent version of razor allow to pass dynamic values from your model directly into the url, and on both side of the url…
Yes, this is like magic….