1

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)

6
  • There's typo error in Url.Actio. Correct it. Commented Aug 16, 2019 at 6:35
  • @RahulNikate thanks, fixed, but got same error Commented Aug 16, 2019 at 6:37
  • Where you are writing your Jquery code? Is it in the .cshtml or separate .js file. Commented Aug 16, 2019 at 6:38
  • @RahulNikate in .js file, Partial view created in cshtml Commented Aug 16, 2019 at 6:40
  • Please see my answer for your error. Thank you @qunzor. Also let me know if that works for you. Commented Aug 16, 2019 at 7:00

1 Answer 1

1

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

        }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.