.net MVC2 jQuery 无法从控制器调用操作

发布于 2024-10-03 01:23:22 字数 1719 浏览 0 评论 0原文

你好 我是 MVC 和 jQuery 的新手,我遵循了在网上找到的示例,但我一直坚持 我的页面上有 img 元素,我试图通过 jQuery 单击事件添加该元素,然后从我的控制器调用操作。

我的页面

<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>About</h2>
<p>
    Put content here.
</p>
<img id="img1" alt="some image" src="http://www.google.pl/logos/2010/stevenson10-hp.jpg" />

<script type="text/javascript" language="javascript">
    $("#img1").click(function (e) {
        $.ajax({
            type: "POST",
            url: "Home/CheckAge",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                alert("ok");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus+" - "+errorThrown);
            }
        });
        return false;
    });       
</script>

添加了事件,但是当我单击图像时,我总是会遇到错误函数 警报显示“错误 - 未定义”

我的控制器看起来像这样

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public static string Test()
    {
        string name = "aaa";
        return "Hello " + name;
    }

    [HttpPost]
    public JsonResult CheckAge(String code)
    {
        return Json("abc");
    }
}

我尝试了很多组合和很多示例,但结果总是相同的 知道我做错了什么吗? 我正在使用 Visual Web Developer 2010 Express

谢谢您的建议

Hi
I'm new to MVC and jQuery, I've followed examples which I've found in net but I have stuck
I have img element on my page to which I'm trying to add via jQuery click event and then invoke action from my controller.

My Page

<asp:Content ID="aboutContent" ContentPlaceHolderID="MainContent" runat="server">
<h2>About</h2>
<p>
    Put content here.
</p>
<img id="img1" alt="some image" src="http://www.google.pl/logos/2010/stevenson10-hp.jpg" />

<script type="text/javascript" language="javascript">
    $("#img1").click(function (e) {
        $.ajax({
            type: "POST",
            url: "Home/CheckAge",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                alert("ok");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus+" - "+errorThrown);
            }
        });
        return false;
    });       
</script>

event is added, but when I click on image I always end up on error function
and alert says "error - undefined"

my controller look like this

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View();
    }

    public ActionResult About()
    {
        return View();
    }

    public static string Test()
    {
        string name = "aaa";
        return "Hello " + name;
    }

    [HttpPost]
    public JsonResult CheckAge(String code)
    {
        return Json("abc");
    }
}

I've tried many combinations and many examples but result is allways the same
Any idea what I'm doing wrong??
I'm Using visual web developer 2010 express

Thx for your advice

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

胡大本事 2024-10-10 01:23:22

您的 CheckAge 方法需要一个参数:

[HttpPost]
public JsonResult CheckAge(String code)
{
    return Json("abc");
}

但是您没有在 AJAX 中传递参数:

data: "{}",

您还需要将脚本代码包装在 $(document).ready() 中:

$(document).ready(function () {
    $("#img1").click(function (e) {
        $.ajax({
            type: "POST",
            url: "Home/CheckAge",
            data: {code: "theCode"},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                alert("ok");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus+" - "+errorThrown);
            }
        });
        return false;
    });  
});

Your CheckAge method takes a parameter:

[HttpPost]
public JsonResult CheckAge(String code)
{
    return Json("abc");
}

But you aren't passing a parameter in the AJAX:

data: "{}",

You also need to wrap your script code in a $(document).ready():

$(document).ready(function () {
    $("#img1").click(function (e) {
        $.ajax({
            type: "POST",
            url: "Home/CheckAge",
            data: {code: "theCode"},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                alert("ok");
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus+" - "+errorThrown);
            }
        });
        return false;
    });  
});
愛上了 2024-10-10 01:23:22

您正在将 contentType = application/json 设置为请求,但控制器上没有任何内容可以理解这一点。默认模型绑定器仅适用于标准查询字符串参数 (application/form-url-encoded)。所以你可以尝试这个:

$('#img1').click(function (e) {
    $.ajax({
        type: 'POST',
        url: '<%= Url.Action("CheckAge") %>',
        data: { code: 'some code you want to send' },
        dataType: 'json',
        cache: false,
        success: function (msg) {
            alert(msg.result);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus+" - "+errorThrown);
        }
    });
    return false;
}); 

控制器操作:

[HttpPost]
public ActionResult CheckAge(string code)
{
    return Json(new { result = "abc" });
}

注意 contentType 不再使用,数据哈希包含将发送到控制器操作的代码参数,并且 url 不再硬编码,而是使用 url helper 来计算它。此外,控制器操作使用匿名对象返回 JSON。

You are setting contentType = application/json as request but there's nothing on the controller to understand this. The default model binder works only with standard query string parameters (application/form-url-encoded). So you could try this:

$('#img1').click(function (e) {
    $.ajax({
        type: 'POST',
        url: '<%= Url.Action("CheckAge") %>',
        data: { code: 'some code you want to send' },
        dataType: 'json',
        cache: false,
        success: function (msg) {
            alert(msg.result);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus+" - "+errorThrown);
        }
    });
    return false;
}); 

And the controller action:

[HttpPost]
public ActionResult CheckAge(string code)
{
    return Json(new { result = "abc" });
}

Notice how the contentType is no longer used, the data hash contains the code parameter which will be sent to the controller action and the url is no longer hardcoded but url helper is used to calculate it. Also the controller action returns JSON using an anonymous object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文