使用 jquery ajax 将参数传递给控制器 [英] Pass a parameter to a controller using jquery ajax

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

问题描述

我已经创建了一个视图和一个控制器,我想要返回一些搜索结果的控制器.我正在使用 jquery 调用控制器

I have created a view and a controller, the controller I am wanting to return some search results. I am calling the controller using jquery

   <input type="text" id="caption" />
        <a href="#" id="search">Search</a>
        <script>
            $("#search").click(function () {
                alert('called');
                var p = { Data: $('#search').val() };
                $.ajax({
                    url: '/Ingredients/Search',
                    type: "POST",
                    data: JSON.stringify(p),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        alert(data);
                    },
                    error: function () {
                        alert("error");
                    }
                });
            });

我的控制器看起来像这样

My controller looks like this

 [HttpPost]
    public ActionResult Search(string input)
    {
        var result = _db.Ingredients.Where(i => i.IngredientName == input);

        return new JsonResult() {Data = new {name="Hello There"}};
    }

我的问题是我不知道如何从我的 jquery 调用中获取变量到控制器中,我在控制器上放置了一个断点并且它被命中但是输入字符串总是空的.

My problem is I am not sure how to get the varible from my jquery call into the controller, I have put a breakpoint on the controller and its been hit however the input string is always null.

我做错了什么?

推荐答案

<input type="text" id="caption" />
@Html.ActionLink("Search", "Search", "Ingredients", null, new { id = "search" })

然后在一个单独的 javascript 文件中不显眼地 AJAX 化这个链接:

and then unobtrusively AJAXify this link in a separate javascript file:

$(function() {
    $("#search").click(function () {
        $.ajax({
            url: this.href,
            type: 'POST',
            data: { input: $('#caption').val() },
            success: function (result) {
                alert(result.name);
            },
            error: function () {
                alert("error");
            }
        });
        return false;
    });
});

您的控制器操作可能如下所示:

where your controller action could look like this:

[HttpPost]
public ActionResult Search(string input)
{
    var result = _db.Ingredients.Where(i => i.IngredientName == input);
    // TODO: Use the result variable in the anonymous object
    // that is sent as JSON to the client
    return Json(new { name = "Hello There" });
}

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

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