Creating a Form and Inserting Data into a Database using .NET MVC

In this blog, we will be creating a form in .NET MVC to insert data into a database. We will follow the below steps to achieve our goal:

Step 1: Create a new ASP.NET MVC project Firstly, create a new ASP.NET MVC project in Visual Studio. Select File > New > Project > Web > ASP.NET Web Application. Give the project a name and select MVC as the project template.

Step 2: Create a model class Create a new class called Employee with properties Name, Email, Age, and Country. Use the [Required] attribute to make sure that the required fields are filled in by the user. For the Country property, we will be using a dropdown list.
public class Employee
{
    [Required]
    public string Name { get; set; }

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

    [Required]
    public int Age { get; set; }

    [Required]
    public string Country { get; set; }
}
Step 3: Create a view Create a new view by right-clicking on the Views folder and selecting Add > View. Name the view InsertEmployee.cshtml. In the view, create a form that will allow the user to enter the employee details. Use the HTML Helper functions to create the form fields.
@model Employee

@{
    ViewBag.Title = "Insert Employee";
}

Insert Employee

@if(!String.IsNullOrEmpty(ViewBag.Message)) {
@ViewBag.Message
} @using(Html.BeginForm()) { @Html.LabelFor(m => m.Name) @Html.TextBoxFor(m => m.Name)
@Html.LabelFor(m => m.Email) @Html.TextBoxFor(m => m.Email)
@Html.LabelFor(m => m.Age) @Html.TextBoxFor(m => m.Age)
@Html.LabelFor(m => m.Country) @Html.DropDownListFor(m => m.Country, new SelectList(new[] {"USA", "Canada", "Mexico"}))
}
Step 4: Create a controller Create a new controller called EmployeeController. In the controller, create a GET action that will return the view, and a POST action that will handle the form submission.
public class EmployeeController : Controller
{
    [HttpGet]
    public ActionResult InsertEmployee()
    {
        return View();
    }

    [HttpPost]
    public ActionResult InsertEmployee(Employee employee)
    {
        if (ModelState.IsValid)
        {
            // Insert data into database using ADO.NET

           
        }
        else
        {
            return View(employee);
        }
    }

    public ActionResult Success()
    {
        return View();
    }
}
Step 5: Insert data into the database using ADO.NET In the POST action of the EmployeeController, use ADO.NET to insert the employee data into the database. First, create a connection to the database using the SqlConnection class. Then, create a SqlCommand object with the SQL query to insert the data. Use the parameters of the SqlCommand object to pass in the employee data. Finally, execute the query using the ExecuteNonQuery method of the SqlCommand object.
[HttpPost]
public ActionResult InsertEmployee(Employee employee)
{
    if (ModelState.IsValid)
    {
        string connectionString = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=EmployeeDatabase;Integrated Security=True";
        string insertQuery = "INSERT INTO Employee(Name, Email, Age, Country) VALUES(@Name, @Email, @Age, @Country)";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(insertQuery, connection);
            command.Parameters.AddWithValue("@Name", employee.Name);
            command.Parameters.AddWithValue("@Email", employee.Email);
            command.Parameters.AddWithValue("@Age", employee.Age);
            command.Parameters.AddWithValue("@Country", employee.Country);

            connection.Open();
            command.ExecuteNonQuery();
        }

        ViewBag.Message = "Employee data inserted successfully.";
    }
    else
    {
        ViewBag.Message = "There are some errors on the page.";
        return View(employee);
    }

    return View();
}

Step 8: Test the application Build and run the application. Navigate to the InsertEmployee view by going to http://localhost:/Employee/InsertEmployee. Fill in the form with the employee details and click the Submit button. If the data is valid, you will be redirected to the Success view with a success message. Check the database to make sure that the employee data has been inserted correctly.

Conclusion

In this blog, we have created a form in .NET MVC to insert data into a database using ADO.NET. We have used a model class to bind the data, created a view to display the form, and used a controller to handle the form submission. We have also used ADO.NET to insert the data into the database and returned a success or failure message to the user.
 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
7 + 8 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice