Thursday, 17 May 2012

how to save data in MVC using JSON

Add a class in the model the code is

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication36.Models
{
    public class Test
    {
        public int EID
        {
            get;
            set;
        }
        public string NAME
        {
            get;
            set;
        }
    }
}

Code of the Controllers

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication36.Models;

namespace MvcApplication36.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        DataClasses1DataContext o = new DataClasses1DataContext();
        public ActionResult Index()
        {
            return View();
        }
      
        public JsonResult x(string a,string b)
        {
            EMP p = new EMP();
            p.EID = Convert.ToInt32(a);
            p.NAME = b;
            o.EMPs.InsertOnSubmit(p);
            o.SubmitChanges();
            return Json(p, JsonRequestBehavior.AllowGet);
        }
      
        public ActionResult About()
        {
            return View();
        }
    }
}

View code is

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication36.Models.Test>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript" src="../../Scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="../../Scripts/MicrosoftMvcValidation.js"></script>
    <script type="text/javascript" src="../../Scripts/MicrosoftMvcAjax.js"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(
function () {

    $('#btn').click(
function () {
    $.getJSON('/Home/x', { a: $('#EID').val(), b: $('#NAME').val() }, function (data) {
        alert('One record saved.');

    });

}
)
}
)
    </script>
    <%Html.EnableClientValidation(); %>
    <%using (Html.BeginForm())
      { %>
    <form id="f">
    <table align="center">
        <tr>
            <td>
                EID
            </td>
            <td>
                <%=Html.TextBoxFor(Model=>Model.EID) %>
            </td>
        </tr>
        <tr>
            <td>
                NAME
            </td>
            <td>
                <%=Html.TextBoxFor(Model=>Model.NAME) %>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <input type="button" id="btn" value="Save" />
            </td>
        </tr>
    </table>
    </form>
    <%} %>
</asp:Content>

1 comment: