Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

javascript - jquery load call to controller and populate div element

I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.

I am passing a custom object as a parameter as well.

var mycustomObject = {
    obj1:value1,
    obj2:value2,
    ..
}

The following does not work...(an i have tried other combinations as well..i get server not found error)

$("#myresults").load ('@Url.Action("MyActionMethod","Home")',mycustomObject);

while the following works

$("#myresults").load('/Home/MyActionMethod', mycustomObject);

While the last statement works, it works only on localhost.

Whats the right syntax to use for jquery load with Url.Action ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@Url.Action() will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "@Url.Action("MyActionMethod","Home")".

Options to solve this include

  1. moving the code into the view or its layout
  2. declaring a global variable in the view - var url = '@Url.Action("MyActionMethod","Home")'; an in the external file use $("#myresults").load(url, mycustomObject);
  3. assign the url to an element as a data-* attribute, for example <button type="button" id="loadSomething" data-url="@Url.Action("MyActionMethod","Home")">...</button>,and in the external file

    $('#loadSomething').click(function() {
        var url = $(this).data('url');
        $("#myresults").load(url, mycustomObject);
    });
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...