Send to and get value from a MVC3 controller by AJAX

前端 未结 1 855
梦毁少年i
梦毁少年i 2021-01-14 12:13

I have a html input text field and a button.

I want to take user input value from that html text field by clicking that button and want to send that value (by AJAX)

1条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 12:33

    Button click event

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

    You call your ajax function like so:

    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");
                }
            }
        });
    }
    

    This is the action that is being called

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

    0 讨论(0)
提交回复
热议问题