Saturday, 8 July 2017

Create a simple form using asp.mvc and c#

Objective :
  • Create a basic form 
  • Save the form values in database using ajax.
We will learn how to post the data using jQuery Ajax post method in MVC which will insert the data asynchronously into the database without whole page post back.

Step 1: Create an MVC application.
  1. In "Microsoft Visual Studio 2012 or above".
  2. "File", then "New" and click "Project" then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click on OK. 
  3. Choose MVC empty application option and click on OK
Step 2: Create Model Class.
Right click on Model folder in the created MVC application, give the class name muserModel or as you wish and click OK.

muserModel.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace MvcProject.Models
{
    public class muserModel
    {
        public string UserName { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }
        public int Attempt { get; set; }
        public int ModuleId { get; set; }

        private SqlConnection con;
       
        //To Handle connection related activities  
        private void connection()
        {
            string constr = ConfigurationManager.ConnectionStrings["SampleDbEntities"].ToString();
            con = new SqlConnection(constr);

        }
        //To add Records into database    
        public int CreateUser(muserModel obj)
        {
            connection();
            SqlCommand com = new SqlCommand("Usp_CreateUser", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@UserName", obj.UserName);
            com.Parameters.AddWithValue("@Email", obj.Email);
            con.Open();
            int i = com.ExecuteNonQuery();

            con.Close();
            return i;
        }
    }
}

Step 3: Create Table and Stored procedures.

Now before creating the views let us create the table named tblperson in the database Sampledb according to our model fields to store the details:

Script of table 

CREATE TABLE [dbo].[tblPerson](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserName] [varchar](50) NULL,
[Email] [varchar](max) NULL,
[Age] [int] NULL,
[Attempt] [int] NULL,
[ModuleId] [int] NULL,
 CONSTRAINT [PK_tblPerson] PRIMARY KEY CLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
 CONSTRAINT [tbl_person_Ukey] UNIQUE NONCLUSTERED 
(
[Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Stored Procedure

Create Proc [dbo].[Usp_CreateUser] 
@UserName varchar(100),
@Email varchar(100)
As
Begin
  if not exists (select UserName from tblPerson where UserName=@UserName)
  begin
    Insert tblPerson (UserName, Email) Values (@UserName, @Email)
    select @@IDENTITY
  End
  else
  begin
   select -1
  end
End

Add connection string in web.config

<connectionStrings>
<add name="SampleDbEntities" connectionString="data source=VIKASH-PC\SQLEXPRESS;initial catalog=SampleDb;integrated security=True;" />
</connectionStrings>
</configuration>

Step 4: Add controller class.

Right click on Controller folder in the created MVC application; give the class name. I have given class name Home and clicked OK.

HomeControlle.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcProject.Models;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace MvcProject.Controllers
{
    public class HomeController : Controller
    {      
        public ActionResult Index()
        {
            return View();
        }
               
        [HttpPost]
        public ActionResult Index(muserModel obj)
        {
            var isSuccess = false;
            var message = "";
            int i = obj.CreateUser(obj);
            if (i > 0)
            {
                isSuccess = true;
                message = "The data has been processed!";
            }
            else
            {
                isSuccess = false;
                message = "The data has not been processed!";
            }
            var jsonData = new { isSuccess, message };
            return Json(jsonData);
        }      
    }
}


Step 5: Add View

Right click on View folder of created MVC application project and add empty view named Index.cshtml and create jQuery Post method to call controller.

To work with jQuery we need to reference jQuery library .You can use the following CDN jQuery library from any provider such as Microsoft,Google or jQuery .
https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js  
If you don't have an active internet connection then you can use the following offline jQuery library as well:

Index.chtml view

@{
    ViewBag.Title = "Create User";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#btnSave").click(function () {

            $("#result").html("");
            var letterNumber = /^[0-9a-zA-Z]+$/;
            //var email = /^[A-Z0-9._%+-]+@@[A-Z0-9.-]+\.[A-Z]{2,4}$/;
            var email=/^(([^<>()[\]\\.,;:\s@@\"]+(\.[^<>()[\]\\.,;:\s@@\"]+)*)|(\".+\"))@@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

            if ($("#txtName").val().match(letterNumber)) {
                if ($("#txtEmail").val().match(email))
                {
                    $.ajax(
                    {
                        type: "POST",
                        url: "Home/Index",
                        data: {
                            UserName: $("#txtName").val(),
                            Email: $("#txtEmail").val()
                        },
                        complete: function () {
                        },
                        success: function (data) {
                            if (data.isSuccess) {
                                alert("Success! " + data.message);
                            } else {
                                alert("Failed! " + data.message);
                            }
                        }
                    });
                }
                else{
                    $("#txtEmail").focus();
                    $("#result").html("Please enter valid email.");
                }
            }
            else {
                $("#txtName").focus();
                $("#result").html("User Name can have characters and numbers only.");
            }
        });
    });
</script>

User Name :
<br />
<input type="text" id="txtName" /><br />
Email :
<br />
<input type="text" id="txtEmail" />
<br />
<br />
<button type="button" id="btnSave">Save</button>
<br />
<div id="result"></div>

Run the application and enter the details into the following form.



No comments:

Post a Comment