使用JQuery ajax调用来调用控制器 [英] calling controller using JQuery ajax calls

查看:68
本文介绍了使用JQuery ajax调用来调用控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户控件,其中包含3个文本框和一个按钮 添加到aspx页面.单击时,它应该对控制器进行ajax调用并传递文本框的数据,并且应该返回一条消息....我该怎么做

i have a user control contains 3 textboxes and a button added to a aspx page . When clicked it should make a ajax call to controller and pass data of textboxes and it should return a message....how can i do this

推荐答案

示例:

<input type="text" name="foo" id="foo" />
<input type="text" name="bar" id="bar" />
<input type="text" name="baz" id="baz" />
<%= Html.ActionLink("send to controller", "Ajax", "Home", null, new { id = "ajaxLink" }) %>

,并且在单独的javascript文件中,您可以使该链接无效:

and in a separate javascript file you could ajaxify this link:

$(function() {
    $('#ajaxLink').click(function() {
        var data = { 
            foo: $('#foo').val(),  
            bar: $('#bar').val(),  
            baz: $('#baz').val()
        };
        $.getJSON(this.href, data, function(result) {
            alert(result.message);
        });
        return false;
    });
});

以及相应的控制器操作,该操作将接收调用并返回JSON:

and the corresponding controller action which will receive the call and return JSON:

public class HomeController: Controller
{
    public ActionResult Ajax(string foo, string bar, string baz)
    {
        // TODO: do something with the arguments

        return Json(
            new { message = "Thanks for sending info" }, 
            JsonRequestBehavior.AllowGet
        );
    }
}

var data分配值时,删除了新"关键字.

Removed the "new" keyword when assigning the value for var data.

这篇关于使用JQuery ajax调用来调用控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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