Reputation: 31
I work with asp.net
and I have some issues.
I created partial view with error message and I want to call view using jQuery
.
I have already created function
in controller
which returns a partial view. But I am stuck with ajax, all time I get errors.
Controller:
[HttpGet]
public ActionResult LoadPartialView()
{
return PartialView("_ErrorMessageWindow");
}
jQuery:
$.ajax({
url: "@(Url.Action('LoadPartialView'))",
type: "GET",
cache: false,
datatype: 'html',
success: function (data) {
}
});
Error:
jquery-3.3.1.min.js:2 GET https://localhost:5001/@(Url.Action('LoadPartialView'))?_=1565937416181 404 (Not Found)
Upvotes: 1
Views: 747
Reputation: 6337
Reason for not working:
@Url.Action()
is Razor server side code and that will not be parsed in external .js
files.
Solution:
Create this <div>
in your .cshtml
:
<div id="partial-view-url" data-request-url="@Url.Action("LoadPartialView", "ControllerName")"></div>
then get Partial View Url in your separate/external .js
file using data-request-url
like below:
$("#partial-view-url").data('data-request-url');
So your $.Ajax
will become like this:
$.ajax({
url: $("#partial-view-url").data('data-request-url'),
type: "GET",
cache: false,
datatype: 'html',
success: function (data) {
}
});
Another way is to declare global variable:
Create global variable in your main .cshtml
file and use it in your external .js
file.
//Declare this variable in your main `.cshtml` file.
var partial-view-url = @Url.Action("LoadPartialView","ControllerName");
//and then use it in your separate/external `.js` file.
$.ajax({
url: partial-view-url,
type: "GET",
cache: false,
datatype: 'html',
success: function (data) {
}
});
Upvotes: 1