Wednesday 7 June 2017

Pass (Send) TextBox values from View to Controller using jQuery in ASP.Net MVC

Pass (Send) TextBox values from View to Controller using jQuery in ASP.Net MVC
Description:
In this example we explain that how to pass TextBox values from View to Controller using jQuery in Asp.Net MVC. Or how to send TextBox values from View to Controller using jQuery in Asp.Net MVC.

Here we will send the TextBox value as a parameter in jQuery Ajax method call and its value will be accessible in controller’s Action Method.

Here we demonstrate how to access @Html.TextBoxFor value in Controller or how to access value of the control from View to Controller.
Controller:
public class EmployeeController : Controller
{
    
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public JsonResult WebMethod(string name)
    {
        EmployeeModel employee = new EmployeeModel
        {
            Name = name,
            DateTime = DateTime.Now.ToString()
        };
        return Json(employee);
    }
}

View:

@model jQuery_AJAX_MVC.Models.EmployeeModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <input type="text" id="txtName"/>
    <input type="button" id="btnGet" value="Get Current Time"/>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnGet").click(function () {
                $.ajax({
                    type: "POST",
                    url: "/Employee/WebMethod",
                    data: '{name: "' + $("#txtName").val() + '" }',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert("Hello: " + response.Name + " .\nCurrent Date and Time: " + response.DateTime);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
    </script>
</body>
</html>



This entry was posted in :

0 comments:

Post a Comment