Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

How to make a form and insert data into database using MVC4.0 razor

Dec 11, 2014
Introduction:

Here in this post I will show you how to make a form (you can say a contact form containing name,email,phone no, message) and how to save the inputted value of the form into database using MVC4.0 using Razor view engine.

Description :

Previously I have shown Show data from a database table content in MVC 4.0 razor and in this post I will show you how to make a form and also save the data into db using MVC4.0.


So first create or choose an existing database and create a table named tblComment.



Now start a MVC project and choose Razor as a view engine. 

After creation of the project select the Model folder and create a class named CommentDateLayer. Its not necessary to create this class within the Modal folder. You can put this any where you want. This class will contain the method to insert the data into db. 

Before that make another class named Comment in the model folder. This class will reflect the table tblComment.

public class Comment
{
   [Required]
   public string Name { get; set; }

   [Required]
   public string Email { get; set; }

   [Required]
   [DataType(DataType.MultilineText)]
   public string Message{ get; set; }

   public int PostId { get; set; } 
}

Now in the ComentDataLayer  class add a method named AddComment.

public int AddEmplyee(Comment cmt)
{
     SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["BlogContext"].ToString());

     string sql = "INSERT INTO [mvc_demo].[dbo].[tblComment]([Name],[Email],[Message]) "+
                            " VALUES "+
                         " ('"+cmt.Name+"','"+cmt.Email+"','"+cmt.Message+"')";
     SqlCommand cmd = new SqlCommand(sql,con);
     con.Open();
     int i =cmd.ExecuteNonQuery();
     con.Close();
     return i;
}

Now its time to do operation with the Controller. The main thing to do. :)

So create a Controller class within the Controller folder named CommentController.
Add the namespace using MvcApplication1.Models; for accessing the model folder into your Controller class. If you put the classes in any other folder add that folder name as namespace.

I took Index as the ActionMethod, so there will be two Action method named Index, one HttpGet and another one HttpPost. The first one for just showing the form and second one is for getting the value after submit button click. We don't need to write any code within the first method(ie, HttpGet). But in the second method(ie, HttpPost) write down the code.

[HttpGet]
public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(FormCollection frm)
{
    Comment c = new Comment();
    c.Name = frm["Name"];
    c.Email = frm["Email"];
    c.Message = frm["Message"];
    CommentDataLayer cmnt = new CommentDataLayer();
    if (cmnt.AddEmplyee(c) == 1)
    {
        ViewBag.Status = "Submitted !";
    }
    return View();
}

FormCollection is an inbuilt class for this you can follow this link.

Now create the View part. To create the View right click on the Action Method and keep the name as it is. Just one change you have to do. Check the Create Strongly typed view and choose Comment as your Modal class. Now click on the Add  button to make your View.

In the view we have to make form first. To create a form we have to use Html.BeginForm() and within that you have to put labels, textboxes and buttons.

So lets create our own form.

@if (!string.IsNullOrEmpty(ViewBag.Status))
{
    
}

@using (Html.BeginForm())
{
   @Html.LabelFor(model => model.Name)
   

   @Html.EditorFor(model => model.Name)
   @Html.ValidationMessageFor(model => model.Name)
   


   @Html.LabelFor(model => model.Email)
   

   @Html.EditorFor(model => model.Email)
   @Html.ValidationMessageFor(model => model.Email)
   


   @Html.LabelFor(model => model.Message)
   

   @Html.EditorFor(model => model.Message)
   @Html.ValidationMessageFor(model => model.Message)
   
}

All the classes are ready. Form is ready now what are you waiting for? Run the project and test it.

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

18 comments :

Unknown said...

Sir your rocking! great tutorial....Thank you

Anonymous said...

wow great

Unknown said...

Nice thanks Arko

Pankaj Chaudhary said...

Yes, Its nice post and running successfully. Thanks

Arka said...

Thanks to everyone .... :)

Anonymous said...

very helping... thank you

Unknown said...

can any one help me how to enter multiple form data into single table database ...???
actually i making a project and in this project 1 page is for registration after register the form automatically open the 2nd page for user details like address and after continue the 2nd page another page open for qualification then submit but when is submit the data only registration page data is entered into the table please anyone give me the solution or code to add data into the column

Anonymous said...

Sir, plz correct the class named CommentDateLayer and when you make the obj of this you used CommentDataLayer cmnt = new CommentDataLayer(); Error in Spelling of CommentDateLayer and CommentDataLayer

Anonymous said...

Validations not work

James said...

Dear I need your help!

is this correct?

public ActionResult Contact()
{



return View();

}


Public ActionResult Contact(Contact cont)
{

Contact new = contac Contact
{

SqlConnection con = new SqlConnection(Connection String());

string sql = "INSERT INTO [mvc_demo].[dbo].[tblContact ]([Name],[Email],[Message]) "+
" VALUES "+
" ('"+cmt.Name+"','"+cmt.Email+"','"+cmt.Message+"')";
SqlCommand cmd = new SqlCommand(sql,con);
con.Open();
int i =cmd.ExecuteNonQuery();
con.Close();


}
return View ("Success full sent");
}

Unknown said...

sir how can i save to database of checkbox value and drop dawn value of asp.net

Unknown said...

plz send me simple example

Unknown said...

pls send it simple coding with demo

Gameplay Short said...

Thanks ASP.NET Suresh ..

Anonymous said...

good but you need validation on from

Anonymous said...

hello sir i want to create simple application which add,update,delete,and view data from table using asp.net and angular.js plz can u explain it

Vinay Chanumolu said...

Man I have been working on 3 tier architecture for about an year and had no idea about MVC and came to this blog and read a few examples and now i am pretty confident :) Great Tutorial Man!

sanjubaba said...
This comment has been removed by the author.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.