Send to and get value from a MVC3 controller by AJ

2020-03-26 04:08发布

问题:

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) into a MVC3 Controller ( as like as a parameter of an ActionResult setValue() ) ?

An other thing i want to know that, how i can get a return value (that return by a ActionResult getValue() ) from a MVC3 Controller and set it in a html text field (by AJAX) ?

please help me with a good example, please. and sorry for my bad English. :)

回答1:

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