Thursday 4 July 2013

MVC3 - Action method Calling with JSON and AJAX

this Article describes how to Call a Action Method In Controller with JSON or AJAX. there are different ways to Call the Action .you can call action  by using  $.post() , $.getJSON(), $.ajax({}) etc.
for better experience first Create a new MVC3 Project with Razor ViewEngion.
this demo send model data from UI to server in json formet and vice versa.

add a new Controller named "UserController" and add a Model Class named "UserModel".

UserModel.cs file looks like:

    [Serializable]
    public class UserModel
    {
        public string loginId { get; set; }
        public string Password { get; set; }
        public string rights { get; set; }
        //public int id {get; set;}
        public string Message { get; set; }
    }


add an Action in UserController class:


        [HttpPost]
        public ActionResult Save(UserModel um)
        {
           
            string message = string.Format("Created user '{0}' in the system.", um.loginId);
            return Json(new UserModel { Message = message });
        }
 Add a View for index action in UserController.
@using (Html.BeginForm()){
 <fieldset>
 <legend>User Detail</legend>
 <div>
 <p>@Html.LabelFor(m => m.loginId)</p>
 <p>@Html.TextBoxFor(m => m.loginId)
 </p>
 </div>
 <div>
 <p>@Html.LabelFor(m => m.Password)</p>
 <p>@Html.TextBoxFor(m => m.Password)</p>
 </div>
 <div><p>
 @Html.LabelFor(m => m.rights)
 </p><p>
 @Html.TextBoxFor(m => m.rights)
 </p></div>
<div><span id="resultMessage"></span></div><br />
 <p><input type="button" value="Save" id="personCreate" /></p>
 </fieldset>
}


View Looks like :

now add the below Script Code in index.cshtml

<script type="text/javascript">
    $(function () {

        $("#personCreate").click(function () {
            var person = getPerson();
            // poor man's validation
            if (person == null) {
                alert("Specify a LoginID please!");
                return;
            }
                   // take the data and post it via json
                        $.post("User/save", person, function (data) {
                            // get the result and do some magic with it
                            var message = data.Message;
                            $("#resultMessage").text(message);
                        });
        });
    });

    function getPerson() {
        var lid = $("#loginId").val();
        var pass = $("#Password").val();
        var right = $("#rights").val();

        // poor man's validation
        return (lid == "") ? null : { loginId: lid, Password: pass,rights:right };
    }  
    </script>

Output Looks Like This. Enter the Data in textbox and press Save Button. this calls the Save Action specified in UserController Class and return Json Data.this data can be displayed in the same UI Page . see the Script Code above:

now if you want to call a Action by using getJson jst follow the steps:
1- create action method in UserController Class.

        public ActionResult Save_Get(UserModel um1)
        {
            string message = string.Format("Created user '{0}' in the system.", um1.loginId);
            return Json(new UserModel { Message = message }, JsonRequestBehavior.AllowGet);
        }
 2- Replace the yellow background Code in the Script Block with the below Code:

            // take the data and post it via getjson
            $.getJSON("User/Save_Get", person, function (data) {
                // get the result and do some magic with it
                var message = data.Message;
                $("#resultMessage").text(message);
            });




now if you want to call a Action by using Ajax jst follow the steps:
1- Replace the yellow background Code in the Script Block with the below Code:

       $.ajax({
         url: 'User/Save_Get',
         type: 'GET',
         data: person,
         dataType: 'json',
         success: function (data){ var message = data.Message;                    
                                    $("#resultMessage").text(message); },
         error:function(jqXhr,textStatus, errorThrown){alert("Oops");   
                         alert(jqXhr.responseText);alert(jqXhr.status);}
            });
     return false;


I hope this is helpfull for your knowledge and experience. if in this article there are something wrong are problem then plz let me know...

Thanks and Regards
Suraj K Mad.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives