Call Controller Action on TextChange or Keydown using jQuery in ASP.Net MVC

Last Reply 20 days ago By dharmendr

Posted 20 days ago

How to call Controller and action using Textchange or keydown in MVC5 using jquery

Posted 20 days ago

I got solution through this

    $('#_Request.PRNO').change(function () {
        alert('sds');
        
        $.ajax({
            
        url: '@Url.Action("AddGrid", "PurchaseOrder")',
        type: 'post',
        data: {
            Text: $('#_Request.PRNO').val()
        },
        success: function (_result) {
            $('#_Request.PRNO').val(_result.foo);
        }
     });

 


Posted 20 days ago

Hi SUJAYS,

Check this example. Now please take its reference and correct your code.

Model

public class PersonModel
{
    public string Name { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    public JsonResult GetData(string name)
    {
        string message = "Name : " + name + "\nDateTime : "
                        + DateTime.Now.ToString("dd/MM/yyyy HH:mm");
        return Json(message);
    }
}

View

@model TextBox_TextChange_jQuery_MVC.Models.PersonModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <h4>Using HTML TextBox</h4>
    <input type="text" name="name" value="" id="txtName" />
    <h4>Using TextBoxFor</h4>
    @Html.TextBoxFor(Model => Model.Name, new { id = "txtName" })
    <h4>Using EditorFor</h4>
    @Html.EditorFor(Model => Model.Name, null, "txtName")
    <h4>Using TextBox</h4>
    @Html.TextBox("txtName")
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("[id$=txtName]").on('change', function () {
                $.ajax({
                    url: '/Home/GetData',
                    type: "POST",
                    data: "{ 'name': '" + $(this).val() + "'}",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        alert(data);
                    }
                });
            });
        });
    </script>
</body>
</html>