Mvc4 Crude operation using FormCollection

Mvc4 Crude using Formcollection

Introduction :  Here in this Tutorial explain Insert Update Delete Operation using the  Formcollection method in mvc4 with the sql server database


Tools :Visual studio 2012 & sql database


Step 1 : First Create sql database with table and Add model with following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel.DataAnnotations;

namespace Mvc_formCollection.Models
{
    public class Employee
    {
        public int id { get; set; }
        [Required]
        public string name { get; set; }
        [Required]
        public string city { get; set; }

        SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11");

        public void insert_data(Employee emp)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into tbl_user values('" + emp.name + "','" + emp.city + "')", con);
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}


Step 2 :  Now Add the controller and type code as below

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

namespace Mvc_formCollection.Controllers
{
    public class ABCController : Controller
    {
       public ActionResult Insert(FormCollection ff)
        {
            if (ModelState.IsValid)
            {
                Employee emp = new Employee();
                emp.name = ff["name"];
                emp.city = ff["city"];
                emp.insert_data(emp);
            }
            return View();
        }
    }
}

Step 4 : Now add view for above Insert Operation

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Employee</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.name)
            @Html.ValidationMessageFor(model => model.name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.city)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.city)
            @Html.ValidationMessageFor(model => model.city)
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

Now run the project and see the o/p


Previous
Next Post »