Friday, 14 July 2017

Additional Resources Helper

Additional Resources Helper : In C# we can have class for addition resource help like for sending mail, to get extension of files etc. We can put the functionality or additional resource helper can and use it whenever required in order save time and amount of code type instead of writing these code again and again.

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Net;
using System.Net.Mail;
using System.IO;

/// <summary>
/// Summary description for Class_AdditionalResourcesHelper
/// </summary>
public class Class_AdditionalResourcesHelper
{
    public Class_AdditionalResourcesHelper()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static void Sendmail(string Toaddrss, string subject, string body, string Displayname, string rplyto)
    {
        MailAddress fromaddress = new MailAddress("mail@gmail.com", Displayname);
        MailAddress Toaddress = new MailAddress(Toaddrss);
        MailMessage mailmessage = new MailMessage(fromaddress, Toaddress);
        mailmessage.ReplyToList.Add(rplyto);
        mailmessage.Body = body;
        mailmessage.Subject = subject;
        mailmessage.IsBodyHtml = true;
        SmtpClient smtpmail = new SmtpClient("smtp.gmail.com", 587);
        smtpmail.EnableSsl = true;

        NetworkCredential credential = new NetworkCredential("mail@gmail.com", "UserPassword");
        smtpmail.Credentials = credential;
        smtpmail.Send(mailmessage);
    }

    public static void SendAttachmentmail(string toadd, string subject, string body, string Displayname, string FilePath)
    {
        MailAddress fromaddress = new MailAddress("mail@gmail.com", Displayname);
        MailAddress Toaddress = new MailAddress(toadd);
        MailMessage mailmessage = new MailMessage(fromaddress, Toaddress);
        mailmessage.Body = body;
        mailmessage.Subject = subject;
        mailmessage.IsBodyHtml = true;

        if (File.Exists(FilePath))
        {
            Attachment at = new Attachment(FilePath);

            mailmessage.Attachments.Add(at);
        }

        SmtpClient smtpmail = new SmtpClient("smtp.gmail.com", 587);
        smtpmail.EnableSsl = true;

        NetworkCredential credential = new NetworkCredential("mail@gmail.com", "UserPassword");
        smtpmail.Credentials = credential;
        smtpmail.Send(mailmessage);
    }

    public static void Sendmail2(string toadd, string subject, string body, string Displayname)
    {
        try
        {
            MailAddress fromaddress = new MailAddress("mail@gmail.com", Displayname);
            MailAddress Toaddress = new MailAddress(toadd);
            MailMessage mailmessage = new MailMessage(fromaddress, Toaddress);
            mailmessage.Body = body;
            mailmessage.Subject = subject;
            mailmessage.IsBodyHtml = true;
            SmtpClient smtpmail = new SmtpClient("smtp.gmail.com", 587);
            smtpmail.EnableSsl = true;

            NetworkCredential credential = new NetworkCredential("mail@gmail.com", "UserPassword");
            smtpmail.Credentials = credential;
            smtpmail.Send(mailmessage);
        }
        catch (Exception ex)
        {
        }

    }
    public static void Sendmail1(string toadd, string subject, string body, string Displayname)
    {
        MailAddress fromaddress = new MailAddress("mail@gmail.com", Displayname);
        MailAddress Toaddress = new MailAddress(toadd);
        MailMessage mailmessage = new MailMessage(fromaddress, Toaddress);
        mailmessage.Body = body;
        mailmessage.Subject = subject;
        mailmessage.IsBodyHtml = true;
        SmtpClient smtpmail = new SmtpClient("smtp.gmail.com", 587);
        smtpmail.EnableSsl = true;

        NetworkCredential credential = new NetworkCredential("mail@gmail.com", "UserPassword");
        smtpmail.Credentials = credential;
        smtpmail.Send(mailmessage);
    }

    public static void SendmailWithCC(string toadd, string subject, string body, string Displayname, string cc)
    {
        MailAddress fromaddress = new MailAddress("mail@gmail.com", Displayname);
        MailAddress Toaddress = new MailAddress(toadd);
        MailAddress SendCC = new MailAddress(cc);
        MailMessage mailmessage = new MailMessage(fromaddress, Toaddress);
        mailmessage.CC.Add(SendCC);
        mailmessage.Body = body;
        mailmessage.Subject = subject;
        mailmessage.IsBodyHtml = true;
        SmtpClient smtpmail = new SmtpClient("smtp.gmail.com", 587);
        smtpmail.EnableSsl = true;
        NetworkCredential credential = new NetworkCredential("mail@gmail.com", "UserPassword");
        smtpmail.Credentials = credential;
        smtpmail.Send(mailmessage);
    }

    public static void Sendmail2CC(string Toaddrss, string subject, string body, string Displayname, string rplyto)
    {
        MailAddress fromaddress = new MailAddress("mail@gmail.com", Displayname);
        MailAddress Toaddress = new MailAddress(Toaddrss);
        MailAddress SendCC = new MailAddress("abc@gmail.com");
        MailAddress SendCC2 = new MailAddress("xyz@gmail.com");
        MailMessage mailmessage = new MailMessage(fromaddress, Toaddress);
        mailmessage.CC.Add(SendCC);
        mailmessage.CC.Add(SendCC2);
        mailmessage.ReplyToList.Add(rplyto);
        mailmessage.Body = body;
        mailmessage.Subject = subject;
        mailmessage.IsBodyHtml = true;
        SmtpClient smtpmail = new SmtpClient("smtp.gmail.com", 587);
        smtpmail.EnableSsl = true;

        NetworkCredential credential = new NetworkCredential("mail@gmail.com", "UserPassword");
        smtpmail.Credentials = credential;
        smtpmail.Send(mailmessage);
    }

    public static string Getextention(string Filename)
    {
        string _extention;
        int index;
        index = Filename.IndexOf('.');
        _extention = Filename.Substring(index);
        return _extention;
    }  
}

ADO.NET Helper Class

ADO.NET Helper Class :  The downsides with ADO.NET is that it requires a lot of typing. So ado.net helper help us to reduce amount of code typing.

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

/// <summary>
/// Summary description for Class_SQLHelper
/// </summary>
public class Class_SQLHelper
{
    private SqlCommand cmd = new SqlCommand();
    private SqlConnection conn;
    private bool bool_Status;
    private string str_Error;

    public Class_SQLHelper()
    {
        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring1"].ToString());
    }

    protected void OpenConnection()
    {
        try
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
        }
        catch (NullReferenceException ex)
        {
            OperationStatus = false;
            ErrorMessage = "Error : " + ex.Message;
        }
    }

    protected void CloseConnection()
    {
        try
        {
            if (conn.State != ConnectionState.Closed)
                conn.Close();
        }
        catch (Exception ex)
        {
            OperationStatus = false;
            ErrorMessage = "Error : " + ex.Message;
        }
    }

    public SqlConnection Connection
    {
        get { return conn; }
    }

    public SqlCommand Command
    {
        get { return cmd; }
        set { cmd = value; }
    }

    public bool OperationStatus
    {
        get { return bool_Status; }
        set { bool_Status = value; }
    }

    public string ErrorMessage
    {
        get { return str_Error; }
        set { str_Error = value; }
    }
}

SQLHelper Class

The SqlHelper class is a utility class that can be used to execute commands in a SQL Server database.

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

/// <summary>
/// Summary description for Class_SQLHelper
/// </summary>
public class Class_SQLHelper
{
    private SqlCommand cmd = new SqlCommand();
    private SqlConnection conn;
    private bool bool_Status;
    private string str_Error;

    public Class_SQLHelper()
    {
        conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionstring"].ToString());
    }

    protected void OpenConnection()
    {
        try
        {
            if (conn.State != ConnectionState.Open)
                conn.Open();
        }
        catch (Exception ex)
        {
            OperationStatus = false;
            ErrorMessage = "Error : " + ex.Message;
        }
    }

    protected void CloseConnection()
    {
        try
        {
            if (conn.State != ConnectionState.Closed)
                conn.Close();
        }
        catch (Exception ex)
        {
            OperationStatus = false;
            ErrorMessage = "Error : " + ex.Message;
        }
    }

    public SqlConnection Connection
    {
        get { return conn; }
    }

    public SqlCommand Command
    {
        get { return cmd; }
        set { cmd = value; }
    }

    public bool OperationStatus
    {
        get { return bool_Status; }
        set { bool_Status = value; }
    }

    public string ErrorMessage
    {
        get { return str_Error; }
        set { str_Error = value; }
    }
}

Here we have created Class_SQLHelper to access database. Now we need to inherit this class to other class where we would like to use these resources. For example we have to manage CRUD operation of News so we can create other class like News.cs or Class_News.cs and inherit this class with Class_SQLHelper.cs as shown below :

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

/// <summary>
/// Summary description for Class_News
/// </summary>
public class Class_News : Class_SQLHelper
{
    public int NewsID { get; set; }
    public string Title { get; set; }
    public string NewsImagePath { get; set; }

    public DateTime PostedDate { get; set; }
    public string PostedBy { get; set; }
    public string Description { get; set; }
    public Boolean Status { get; set; }
    public DataTable NewsTable { get; set; }
    public string SearchText { get; set; }

    public Class_News()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public void AddNews()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "USP_AddNews";
            cmd.Parameters.AddWithValue("@Title", Title);
            cmd.Parameters.AddWithValue("@NewsImagePath", NewsImagePath);

            cmd.Parameters.AddWithValue("@PostedDate", PostedDate);
            cmd.Parameters.AddWithValue("@PostedBy", PostedBy);
            cmd.Parameters.AddWithValue("@Description", Description);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = Connection;
            OpenConnection();
            NewsID = Convert.ToInt32(cmd.ExecuteScalar());
            if (NewsID > 0)
            {
                OperationStatus = true;
            }
            else
            {
                OperationStatus = false;
                ErrorMessage = "Error : News not added successfully.";
            }
        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }

    public void UpdateNewsByID()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "USP_UpdateNewsByID";
            cmd.Parameters.AddWithValue("@NewsID", NewsID);
            cmd.Parameters.AddWithValue("@Title", Title);
            cmd.Parameters.AddWithValue("@NewsImagePath", NewsImagePath);

            cmd.Parameters.AddWithValue("@PostedDate", PostedDate);
            cmd.Parameters.AddWithValue("@PostedBy", PostedBy);
            cmd.Parameters.AddWithValue("@Description", Description);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = Connection;
            OpenConnection();
            NewsID = Convert.ToInt32(cmd.ExecuteScalar());
            if (NewsID > 0)
            {
                OperationStatus = true;
            }
            else
            {
                OperationStatus = false;
                ErrorMessage = "Error : News not updated successfully.";
            }
        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }

    public void GetNewsByID()
    {
        try
        {
            SqlDataAdapter ad = new SqlDataAdapter();
            DataTable Sqldatatable = new DataTable();

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "USP_GetNewsByID";
            cmd.Parameters.AddWithValue("@NewsID", NewsID);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = Connection;
            ad.SelectCommand = cmd;
            OpenConnection();
            ad.Fill(Sqldatatable);
            NewsTable = Sqldatatable;
            OperationStatus = true;
            CloseConnection();
            Sqldatatable.Dispose();
            cmd.Dispose();
            ad.Dispose();


        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }

    public void GetAllNews()
    {
        try
        {
            SqlDataAdapter ad = new SqlDataAdapter();
            DataTable Sqldatatable = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "USP_GetAllNews";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@SearchText", SearchText);
            cmd.Connection = Connection;
            ad.SelectCommand = cmd;
            OpenConnection();
            ad.Fill(Sqldatatable);
            NewsTable = Sqldatatable;
            OperationStatus = true;
            CloseConnection();
            Sqldatatable.Dispose();
            cmd.Dispose();
            ad.Dispose();
        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }

    public void GetNews()
    {
        try
        {
            SqlDataAdapter ad = new SqlDataAdapter();
            DataTable Sqldatatable = new DataTable();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "USP_GetNews";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = Connection;
            ad.SelectCommand = cmd;
            OpenConnection();
            ad.Fill(Sqldatatable);
            NewsTable = Sqldatatable;
            OperationStatus = true;
            CloseConnection();
            Sqldatatable.Dispose();
            cmd.Dispose();
            ad.Dispose();
        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }
    public void DeleteNewsByID()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "USP_DeleteNewsByID";
            cmd.Parameters.AddWithValue("@NewsID", NewsID);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = Connection;
            OpenConnection();
            NewsID = Convert.ToInt32(cmd.ExecuteScalar());
            if (NewsID == -1)
            {
                OperationStatus = false;
                ErrorMessage = "Error : Property ID " + NewsID + " does not Exist.";
            }
            else
            {
                OperationStatus = true;
            }
        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }
    public void GetMaxNewsID()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "USP_GetMaxNewsID";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = Connection;
            OpenConnection();
            NewsID = Convert.ToInt32(cmd.ExecuteScalar());
            OperationStatus = true;
            CloseConnection();
            cmd.Dispose();
        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }

    public void UpdateNewsStatusByID()
    {
        try
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "USP_UpdateNewsStatusByID";
            cmd.Parameters.AddWithValue("@NewsID", NewsID);
            cmd.Parameters.AddWithValue("@Status", Status);

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = Connection;
            OpenConnection();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            ErrorMessage = "Error : " + ex.Message;
            OperationStatus = false;
        }
        finally
        {
            CloseConnection();
        }
    }
}

Sunday, 9 July 2017

Create a basic form to add job using asp.net MVC


Create Table Script :

CREATE TABLE [dbo].[tblJob](
[JobId] [int] IDENTITY(1,1) NOT NULL,
[JobName] [varchar](50) NULL,
[JobDesc] [varchar](50) NULL,
[DateFrom] [datetime] NULL,
[DateTo] [datetime] NULL,
[MID] [int] NULL,
[IsActive] [bit] NULL,
 CONSTRAINT [PK_tblJob] PRIMARY KEY CLUSTERED
(
[JobId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

Create Procedure 

Create Proc [dbo].[Usp_CreateJob]
@JobName varchar(50),
@JobDesc varchar(50),
@DateFrom datetime,
@DateTo datetime,
@MID int
As
Begin
if not exists (select JobName from tblJob where JobName=@JobName)
begin
  Insert tblJob values(@JobName,@JobDesc,@DateFrom,@DateTo,@MID,'true')
  select @@IDENTITY
End
else
begin
  select -1
end

end

Create Database Connection

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

Add JobModel.cs in Models Folder

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

namespace MvcProject.Models
{
    public class JobModel
    {
        public string JobName { get; set; }
        public string JobDesc { get; set; }
        public int MID { get; set; }
        public DateTime DateFrom { get; set; }
        public DateTime DateTo { get; set; }
    }

}

Add Controller Methods

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

namespace MvcProject.Controllers
{
    public class Home3Controller : Controller
    {
        public ActionResult Index()
        {
            string connectionstring = ConfigurationManager.ConnectionStrings["SampleDbEntities1"].ToString();
            using (SqlConnection con = new SqlConnection(connectionstring))
            {
                SqlCommand com = new SqlCommand("Usp_ReadMsets", con);
                com.CommandType = CommandType.StoredProcedure;
                con.Open();
                SqlDataReader reader = com.ExecuteReader();

                List<SelectListItem> mset = new List<SelectListItem>();              

                while (reader.Read())
                {
                    mset.Add(new SelectListItem{
                      Value=(reader["MID"].ToString()),
                      Text=reader["MName"].ToString()
                    });
                   
                }
                ViewBag.Msets = mset;          
            }
            return View();
        }

        [HttpPost]
        public ActionResult Index(JobModel job)
        {
            var isSuccess = false;
            var message = "";
            string connectionstring = ConfigurationManager.ConnectionStrings["SampleDbEntities1"].ToString();
            using (SqlConnection con = new SqlConnection(connectionstring))
            {
                SqlCommand com = new SqlCommand("Usp_CreateJob", con);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@JobName", job.JobName);
                com.Parameters.AddWithValue("@JobDesc", job.JobDesc);
                com.Parameters.AddWithValue("@DateFrom",job.DateFrom);
                com.Parameters.AddWithValue("@DateTo", job.DateTo);
                com.Parameters.AddWithValue("@MID", job.MID);

                con.Open();
                int i = com.ExecuteNonQuery();
                if (i > 0)
                {
                    isSuccess = true;
                    message = "The job has been created!";
                }
                else
                {
                    isSuccess = false;
                    message = "The job has not been created!";
                }
                var jsonData = new { isSuccess, message };
                return Json(jsonData);              
            }
           // return View();
        }
    }
}

Add Index.cshtml

@{
    ViewBag.Title = "Create Job";
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    
    <!-- Load jQuery JS -->
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <!-- Load jQuery UI Main JS  -->
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
    $(document).ready(function () {
        $('#txtDateFrom').datepicker({ minDate: '0' });
        $('#txtDateTo').datepicker({ minDate: '0' });

        $("#btnSave").click(function () {
            $("#result").html("");
            if ($("#txtJobName").val()!="") {
                if ($("#txtJobDesc").val()!="")
                {
                    $.ajax(
                    {
                        type: "POST",
                        url: "Home3/Index",
                        data: {

                            JobName: $("#txtJobName").val(),
                            JobDesc: $("#txtJobDesc").val(),
                            DateFrom: $("#txtDateFrom").val(),
                            DateTo: $("#txtDateTo").val(),
                            MID: $("#drpMID").find(":selected").val()
                        },
                        complete: function () {
                        },
                        success: function (data) {
                            if (data.isSuccess) {
                                alert("Success! " + data.message);
                            } else {
                                alert("Failed! " + data.message);
                            }
                        }
                    });
                }
                else{
                    $("#txtJobDesc").focus();
                    $("#result").html("Please enter job desc.");
                }
            }
            else {
                $("#txtJobName").focus();
                $("#result").html("Please enter job name");

            }
        });
    });

</script>
Job Name :
<br />
<input type="text" id="txtJobName" /><br />
Job Desc:
<br />
<textarea id="txtJobDesc"></textarea>
<br />
Date From
<br />
<input type="text" id="txtDateFrom" /><br />
Date To
<br />
<input type="text" id="txtDateTo" /><br />
Mtype
<br />
<select>
    @foreach (var m in @ViewBag.Msets)
    { 
        <option id="drpMID" value= "+@m.Value+">@m.Text </option>      
    }
</select><br />
<br />
<button type="button" id="btnSave">Save</button>
<br />
<div id="result"></div>

Saturday, 8 July 2017

Dropdownlist in asp.net MVC

Create dropdownlist : A dropdownlist in MVC is a collection of SelectListItem objects. Depending on your project requirement you may either hard code the values in code or retrieve them from a database table.

Method 1.)

In Controller Method

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

namespace MvcProject.Controllers
{
    public class Home3Controller : Controller
    {      
        public ActionResult Index()
        {
            //Creating generic list
            List<SelectListItem> ObjList = new List<SelectListItem>()
            {
                new SelectListItem { Text = "Latur", Value = "1" },
                new SelectListItem { Text = "Pune", Value = "2" },
                new SelectListItem { Text = "Mumbai", Value = "3" },
                new SelectListItem { Text = "Delhi", Value = "4" },

            };
            //Assigning generic list to ViewBag
            ViewBag.Locations = ObjList;

            return View();
        }

    }
}


In Index.cshtml view

Mtype
<br />
<select>
    @foreach (var m in @ViewBag.Locations)
    {
        <option value= "+@m.Value+">@m.Text </option>    
    }
</select>

Method 2.) Binding Dropdownlist With Database In asp.net MVC using stored Procedure

Create Table

CREATE TABLE [dbo].[tblMset](
[MID] [int] IDENTITY(1,1) NOT NULL,
[MName] [varchar](50) NULL,
[Status] [bit] NULL,
 CONSTRAINT [PK_tblMset] PRIMARY KEY CLUSTERED
(
[MID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

Create Stored Procedure

Create proc [dbo].[Usp_ReadMsets]
As
Begin
  select * from tblMset where Status='true'
End

Add connection string in web.config

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

Create Controller Method

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

namespace MvcProject.Controllers
{
    public class Home3Controller : Controller
    {
        public ActionResult Index()
        {
            string connectionstring = ConfigurationManager.ConnectionStrings["SampleDbEntities1"].ToString();
            using (SqlConnection con = new SqlConnection(connectionstring))
            {
                SqlCommand com = new SqlCommand("Usp_ReadMsets", con);
                com.CommandType = CommandType.StoredProcedure;
                con.Open();
                SqlDataReader reader = com.ExecuteReader();

                List<SelectListItem> mset = new List<SelectListItem>();              

                while (reader.Read())
                {
                    mset.Add(new SelectListItem{
                      Value=(reader["MID"].ToString()),
                      Text=reader["MName"].ToString()
                    });
                 
                }
                ViewBag.Msets = mset;          
            }
            return View();
        }
    }
}

Add Index.cshtml View

Mtype
<br />
<select>
    @foreach (var m in @ViewBag.Msets)
    {
        <option value= "+@m.Value+">@m.Text </option>    
    }
</select>


Method 3.) For this example, let's use entity framework to retrieve data and bind dropdownlist.

Add ADO.Net Entity Model in Models folder and add database table. Here name of table is tblMset.


A connection string will be added to web.config file like as given below.

 <add name="SampleDbEntities" connectionString="metadata=res://*/Models.UsrModel.csdl|res://*/Models.UsrModel.ssdl|res://*/Models.UsrModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=VIKASH-PC\SQLEXPRESS;initial catalog=SampleDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>


Controller Method

        public ActionResult Index()
        {
            SampleDbEntities db = new SampleDbEntities();
            ViewBag.Msets = new SelectList(db.tblMsets,"MID", "MName");
            return View();
        }

Or Controller Method

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

namespace MvcProject.Controllers
{
    public class Home4Controller : Controller
    {
        public ActionResult Index()
        {
            SampleDbEntities db = new SampleDbEntities();
            ViewBag.Msets = new SelectList(from x in db.tblMsets where x.Status==true select x, "MID", "MName");
            return View();
        }

    }
}

In Index.cshtml view

Mtype
<br />
<select>
    @foreach (var m in @ViewBag.Msets)
    {
        <option value= "+@m.Value+">@m.Text </option>    
    }
</select>


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.



Create a simple form using asp.net mvc.

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.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; }
    }
}

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();
        }

        private SqlConnection con;

         // Create controller method to be called using Ajax        
        [HttpPost]
        public ActionResult Index(muserModel obj)
        {
            var isSuccess = false;
            var message = "";
            int i = 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);
        }

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

        }
        //To add Records into database     
        private 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 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.