简体   繁体   中英

How to call partial view using ajax method from jQuery

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)

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) {

        }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM