jquery加载对控制器的调用并填充div元素 [英] jquery load call to controller and populate div element
问题描述
我的index.cshtml中有一个div元素,ID为#myresults,我试图通过调用mvc控制器方法通过jquery.load方法加载数据。但我无法获得正确的语法。
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);
以下作品
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
虽然最后一个语句有效,但它仅适用于localhost。
While the last statement works, it works only on localhost.
使用Url.Action进行jquery加载的正确语法是什么?
Whats the right syntax to use for jquery load with Url.Action ?
推荐答案
@ Url.Action()
将始终生成正确的URL,因此如果获得404,则表示此代码位于外部脚本文件中。 Razor代码不会在外部脚本中执行,因此您的网址将成为文本@ Url.Action(MyActionMethod,Home)。
@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")".
要解决的选项这包括
- 将代码移动到视图或其布局中
- 声明一个全局变量查看 -
var url =
在外部文件中使用
'@ Url.Action(MyActionMethod,Home)';
$(#myresults)。load(url,mycustomObject);
-
将网址指定为
data - *
属性,例如
< button type =buttonid =loadSomethingdata-url =@ Url.Action (MyActionMethod,Home)> ...< / button>
,以及
外部文件
- moving the code into the view or its layout
- declaring a global variable in the view -
var url = '@Url.Action("MyActionMethod","Home")';
an in the external file use$("#myresults").load(url, mycustomObject);
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);
});
这篇关于jquery加载对控制器的调用并填充div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!