【问题标题】:How to access Http Post values in Action Method when posting using jQuery使用 jQuery 发布时如何在 Action Method 中访问 Http Post 值
【发布时间】:2012-02-25 07:49:00
【问题描述】:

我只是在探索 asp.net mvc,因为我想从 Webforms 切换。我只是在尝试使用 jQuery 发布一个字符串并将该字符串返回到响应中。但是,我不确定如何在控制器的 action 方法中访问 post 参数。

我尝试使用 FormCollection,但它是空的(我想这很明显,因为我使用 jQuery ajax 调用而不是表单发布)

 $(function () {
        $("#GetReport").click(function () {
            $.ajax({
                type: 'POST',
                url: '/Reports/GetReport',
                data: 'Abracadabra Mercedes',
                contentType: 'application/text;charset=utf-8',
                dataType: 'text',
                success: function (result) {
                    alert(result);
                }


            });
        });
    });

//Controller Code
public class ReportsController : Controller
    {
        //
        [HttpPost]
        public ActionResult GetReport(string query)
        {


            ViewBag.Result = "Hello";

            ViewBag.Geronimo = query;

            return View();

        }

    }

        //View Code
@{
    Layout = null;
}

@ViewBag.Result + @ViewBag.Geronimo

【问题讨论】:

    标签: jquery asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    您的“数据”需要是一个键/值列表,例如 URL。然后,您将通过 Action 方法的查询参数获得该信息。

    例如

    $(function () {
        $("#GetReport").click(function () {
            $.ajax({
                type: 'POST',
                url: '/Reports/GetReport',
                data: 'query=Abracadabra Mercedes',
                success: function (result) {
                    alert(result);
                }
    
    
            });
        });
    });
    

    请参阅http://www.tugberkugurlu.com/archive/working-with-jquery-ajax-api-on-asp-net-mvc-3-0-power-of-json-jquery-and-asp-net-mvc-partial-views 了解更多信息。

    在该示例中,您可以看到他正在这样做。寻找:

    var d = "itemId=" + itemId;
    

    编辑:我刚刚在这里尝试过

    <input type="button" value="Click" id="GetReport" />
    <input type="text" id="tester"/>
    
    <h2>Index</h2>
    <script type="text/javascript">
    $(function () {
        $("#GetReport").click(function (e) {
            var d = "input=" + $('#tester').val();
            debugger;
            $.ajax({
                type: 'POST',
                url: '/Home/test',
                data: d,
                success: function (result) {
                    alert(result);
                }
    
            });
    
            if (e && e.preventDefault) {
                e.preventDefault();
            }
        });
    });
    

    public class HomeController : Controller
    {
        [HttpPost]
        public ActionResult Test(string input)
        {
            return new ContentResult() { Content = input };
        }
    

    【讨论】:

    • 好吧,你必须删除内容类型和数据类型,它工作正常。
    • 是的,现在运行良好。非常感谢!我想知道这两个参数有什么影响,它之前没有工作。
    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 2012-01-13
    • 2015-05-22
    相关资源
    最近更新 更多