【问题标题】:Send to and get value from a MVC3 controller by AJAX通过 AJAX 向 MVC3 控制器发送和获取值
【发布时间】:2012-06-29 18:29:59
【问题描述】:

我有一个 html 输入文本字段和一个按钮。

我想通过单击该按钮从该 ​​html 文本字段中获取用户输入值,并希望将该值(通过 AJAX)发送到 MVC3 控制器(就像 ActionResult setValue() 的参数一样)?

我想知道的另一件事是,如何从 MVC3 控制器获取返回值(由 ActionResult getValue() 返回)并将其设置在 html 文本字段中(通过 AJAX)?

请帮我举一个很好的例子。对不起我的英语不好。 :)

【问题讨论】:

    标签: asp.net-mvc-3 jquery


    【解决方案1】:

    按钮点击事件

    $(document).ready(function ()
    {
        $('#ButtonName').click(function ()
        {
            if ($('#YourHtmlTextBox').val() != '')
            {
                sendValueToController();
            }
            return false;
        });
    });
    

    你这样调用你的 ajax 函数:

    function sendValueToController()
    {
        var yourValue = $('#YourHtmlTextBox').val();
    
        $.ajax({
            url: "/ControllerName/ActionName/",
            data: { YourValue: yourValue },
            cache: false,
            type: "GET",
            timeout: 10000,
            dataType: "json",
            success: function (result)
            {
                if (result.Success)
                { // this sets the value from the response
                    $('#SomeOtherHtmlTextBox').val(result.Result);
                } else
                {
                    $('#SomeOtherHtmlTextBox').val("Failed");
                }
            }
        });
    }
    

    这是被调用的动作

    public JsonResult ActionName(string YourValue)
    {
        ...
        return Json(new { Success = true, Result = "Some Value" }, JsonRequestBehavior.AllowGet);
    }
    

    【讨论】:

    • 你的例子你发送一个字符串到那个动作,我如何发送一个数组并从它的索引中获取值?
    • 您应该使用您拥有的代码发布一个新问题,以便我们可以更准确地查看和帮助
    • 我做到了,这是问题链接Catch a JSON array into a MVC3 controller action
    猜你喜欢
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多