jquery加载对控制器的调用并填充div元素 [英] jquery load call to controller and populate div element

查看:267
本文介绍了jquery加载对控制器的调用并填充div元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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")".

要解决的选项这包括


  1. 将代码移动到视图或其布局中

  2. 声明一个全局变量查看 - var url =
    '@ Url.Action(MyActionMethod,Home)';
    在外部文件中使用
    $(#myresults)。load(url,mycustomObject);

  3. 将网址指定为 data - * 属性,例如
    < button type =buttonid =loadSomethingdata-url =@ Url.Action (MyActionMethod,Home)> ...< / button> ,以及
    外部文件

  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);
});


这篇关于jquery加载对控制器的调用并填充div元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆