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

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (24) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (9) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (12) Web Api (10) Web Service (1) XMl (1)