通过AJAX发送并从MVC3控制器获取值

zxp*_*nce 2 jquery asp.net-mvc-3

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

我想通过点击该按钮,采取从HTML文本字段用户输入值,并希望该值(通过AJAX)发送到MVC3控制器(像作为一个ActionResult setValue方法的参数())?

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

请帮我一个很好的例子.抱歉我的英语不好 :)

CD *_*ith 9

按钮单击事件

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

你可以像这样调用你的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");
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

这是被调用的动作

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