model asp.net mvc

Introduction

In this blog, we’ll look at models that use a different library for MVC. When we execute an application, we must use an Action method to indicate the correct controller name. It throws an error if we give the wrong name. Talking about data transfer features Asp.Net MVC facilitates TempData feature which is the most recommended one to use.

However, in the case of Model, we can put the model in the MVC Application where the library can be placed.

Step 1

Create a database table by adding the following command:

Example

Create Table StudentInfo (  

StudentID int identity primary key,  

StudentName nvarchar(50),  

Gender nvarchar(50),  

SchoolName nvarchar(50)  

) GO Insert into StudentInfo  

values  

(‘Munesh’, ‘Male’, ‘VIT’) Insert into StudentInfo  

values  

(‘Rahul’, ‘Male’, ‘ABC’) Insert into StudentInfo  

values  

(‘Reet’, ‘Female’, ‘XYZ’) Insert into StudentInfo  

values  

(‘Anshuman’, ‘Male’, ‘PQR’)  

Make a Stored Procedure to retrieve data from the database as well.

Example

Create procedure GetAllStudents as Begin  

Select  

StudentID,  

StudentName,  

Gender,  

SchoolName  

from  

StudentInfo End  

Step 2

Add a new library to the project now. To add a library to a solution, right-click on the project in the Solution Explorer and choose Add -> New Project.

The New Project screen will appear after that. Select “Windows” -> “Class Library” from that screen, then give the library an appropriate name like “BusinessLayer.”

Change the name of the class from class1.cs to “Student.cs” and define the database properties as we did in the model classes. 

Figure: Change the name of the class from the BusinessLayer Project

Example

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Text;  

namespace BusinessLayer

{

    public class Student

    {

        public int StudentID

        {

            get;

            set;

        }

        public string StudentName

        {

            get;

            set;

        }

        public string Gender

        {

            get;

            set;

        }

        public string StudentClass

        {

            get;

            set;

        }

    }

}

Step 3

Add another class to this library for writing the business logic code and using that we will retrieve the data from the database. Provide this class the name “BusinessLogic.cs”.

Add some ADO.Net references to this library before writing the code for retrieving data from the database. Right-click on the References folder in this library project, then select “System.Configuration” assembly from assemblies.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

namespace BusinessLayer

{

    public class BusinessLogic

    {

        public IEnumerable<Student> student

        {

            get

            {

                string connectionString = ConfigurationManager.ConnectionStrings[“Connect”].ConnectionString;

                List<Student> employees = new List<Student>();

                using (SqlConnection con = new SqlConnection(connectionString))

                {

                    SqlCommand cmd = new SqlCommand(“GetAllStudents”, con);

                    cmd.CommandType = CommandType.StoredProcedure;

                    con.Open();

                    SqlDataReader rdr = cmd.ExecuteReader();

                    while (rdr.Read())

                    {

                        Student student = new Student();

                        student.StudentID = Convert.ToInt32(rdr[“StudentID”]);

                        student.StudentName = rdr[“StudentName”].ToString();

                        student.Gender = rdr[“Gender”].ToString();

                        student.StudentClass = rdr[“SchoolName”].ToString();

                        employees.Add(student);

                    }

                }

                return employees;

            }

        }

    }

}

Build the library project when you’ve completed all of this.

In the web config, the connection string will be:

Example

<connectionStrings>

<add name=”Connect” connectionString=”DataSource=(LocalDb)\MSSQLLocalDb;Initial Catalog=Student;Integrated Security=True”/>

</connectionStrings>

Step 4

Now, right-click on the References folder in your MVC project and add the reference for the library project.

Figure: Add a Reference of BusinessLayer project in Your MVC Project

Step 5

Add a controller to this project by going to the controller folder. This controller’s name should be “Student.” Add the namespace for the BusinessLogic project to this controller.

Example

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Web;  

using System.Web.Mvc;  

using BusinessLayer;  

namespace MvcApplication2.Controllers

{

    public class StudentController : Controller

    {

        public ActionResult Index()

        {

            BusinessLogic BL = new BusinessLogic();

            List<Student> student = BL.student.ToList();

            return View(student);

        }

    }

}

Step 6

Figure: Add the View of Index in the List Template

Add a view to this Controller method by right-clicking on it. Select “Student” as the Model class and “List” as the Scaffold template to build a list for us while generating the view.

Example

@model IEnumerable<BusinessLayer.Student>

@{

    ViewBag.Title = “Index”;

}

<h2>Index</h2>

<p>

    @Html.ActionLink(“Create New”, “Create”)

</p>

<table class=”table”>

    <tr>

        <th>

            @Html.DisplayNameFor(model => model.StudentName)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.Gender)

        </th>

        <th>

            @Html.DisplayNameFor(model => model.StudentClass)

        </th>

        <th></th>

    </tr>

@foreach (var item in Model) {

    <tr>

        <td>

            @Html.DisplayFor(modelItem => item.StudentName)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.Gender)

        </td>

        <td>

            @Html.DisplayFor(modelItem => item.StudentClass)

        </td>

        <td>

            @Html.ActionLink(“Edit”, “Edit”, new { id=item.StudentID }) |

            @Html.ActionLink(“Details”, “Details”, new { id=item.StudentID }) |

            @Html.ActionLink(“Delete”, “Delete”, new { id=item.StudentID })

        </td>

    </tr>

}

</table>

Change the controller name in the Route.config file before running this application.

Example

using System.Web.Mvc;

using System.Web.Routing;

namespace MyWebApplication1

{

    public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

            routes.MapRoute(

                name: “Default”,

                url: “{controller}/{action}/{id}”,

                defaults: new { controller = “Student”, action = “Index”, id = UrlParameter.Optional }

            );

        }

    }

}

Now run your application, you’ll receive output like this:

Figure: Output of MVC Application

Example

[HttpGet]

public ActionResult Edit(int ID)

{

Student student = new Student();

       BusinessLogic BL = new BusinessLogic();

       Student _student = BL.student.Where(c => c.StudentID == ID).SingleOrDefault();

return View(student);

}

When you run your application, you’ll see a grid-like this with all of the data from your database.

Step 7

After that, we’ll need a View, so right-click on this action method and select Edit View.

Figure: Click on the Edit Action method of Index View

Step 8

When we click the EDIT link, we want it to take us to the StudentController’s Index Action method with a specified ID.

So, first, develop an Action method for this, and then a view to change these data.

The action method will be as follows:

[HttpGet]

public ActionResult Edit(int ID)

{

    Student student = new Student();

    BusinessLogic BL = new BusinessLogic();

    Student _student = BL.student.Where(c => c.StudentID == ID).SingleOrDefault();

    return View(student);

}

Figure: Edit view of MVC Application after clicking on Edit Link

After that, View Code will look like this:

Example

@model BusinessLayer.Student

@{

    ViewBag.Title = “Edit”;

    Layout = “~/Views/Shared/_Layout.cshtml”;

}

<h2>Edit</h2>

@using (Html.BeginForm())

{

    @Html.AntiForgeryToken()

<div class=”form-horizontal”>

    <h4>Student</h4>

    <hr />

    @Html.ValidationSummary(true, “”, new { @class = “text-danger” })

    @Html.HiddenFor(model => model.StudentID)

    <div class=”form-group”>

        @Html.LabelFor(model => model.StudentName, htmlAttributes: new { @class = “control-label col-md-2” })

        <div class=”col-md-10″>

            @Html.EditorFor(model => model.StudentName, new { htmlAttributes = new { @class = “form-control” } })

            @Html.ValidationMessageFor(model => model.StudentName, “”, new { @class = “text-danger” })

        </div>

    </div>

    <div class=”form-group”>

        @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = “control-label col-md-2” })

        <div class=”col-md-10″>

            @Html.RadioButtonFor(model => model.Gender, “Male”, new { @checked = true })

            Male

            @Html.RadioButtonFor(model => model.Gender, “Female”)

            Female

        </div>

    </div>

    <div class=”form-group”>

        @Html.LabelFor(model => model.StudentClass, htmlAttributes: new { @class = “control-label col-md-2” })

        <div class=”col-md-10″>

            @Html.EditorFor(model => model.StudentClass, new { htmlAttributes = new { @class = “form-control” } })

            @Html.ValidationMessageFor(model => model.StudentClass, “”, new { @class = “text-danger” })

        </div>

    </div>

    <div class=”form-group”>

        <div class=”col-md-offset-2 col-md-10″>

            <input type=”submit” value=”Save” class=”btn btn-default” />

        </div>

    </div>

</div>

}

<div>

    @Html.ActionLink(“Back to List”, “Index”)

</div>

When you run your application, you’ll see a grid-like this with all of the data from your database.

Figure: Output of the MVC Application

When we click on the Edit link, it will redirect to the EDIT View, which looks like this.

Figure: Edit view of MVC Application 

You can edit the data here and view the updated value after clicking the Save 

Step 9:- Updating Datamodel

When we click the Save button, we get an error because the edit method uses the “[HttpGet]” tag, which signifies that this action only accepts get requests.

Firstly, create the stored procedure for updating the Edit value in the database. So, as a result, the stored procedure will be as follows:

Create the UpdateStudentInfo process.

Example

Create procedure GetAllStudents as Begin  

Select  

StudentID,  

StudentName,  

Gender,  

SchoolName  

from  

StudentInfo Endbutton.

Step 10

Now, open the BusinessLayer Library project and add a save function to the BusinessLogic.cs class to store the data to the database.

Example

public void SaveStudentInfo(Student student)

{

    string connectionString =

        ConfigurationManager.ConnectionStrings[“Connect”].ConnectionString;

    using (SqlConnection con = new SqlConnection(connectionString))

    {

        SqlCommand cmd = new SqlCommand(“UpdateStudentInfo”, con);

        cmd.CommandType = CommandType.StoredProcedure;

        SqlParameter studentId = new SqlParameter();

        studentId.ParameterName = “@StudentID”;

        studentId.Value = student.StudentID;

        cmd.Parameters.Add(studentId);

        SqlParameter studentName = new SqlParameter();

        studentName.ParameterName = “@StudentName”;

        studentName.Value = student.StudentName;

        cmd.Parameters.Add(studentName);

        SqlParameter Gender = new SqlParameter();

        Gender.ParameterName = “@Gender”;

        Gender.Value = student.Gender;

        cmd.Parameters.Add(Gender);

        SqlParameter schoolname = new SqlParameter();

        schoolname.ParameterName = “@SchoolName”;

        schoolname.Value = student.StudentClass;

        cmd.Parameters.Add(schoolname);

        con.Open();

        cmd.ExecuteNonQuery();

    }

}

Step 11

Add an Edit post method to the Student Controller to update the value. Method code will be as follow for Edit the method:

Example

[HttpPost]

public ActionResult Edit()

{

    if (ModelState.IsValid)

    {

        Student student = new Student();

        BusinessLogic BL = new BusinessLogic();

        BL.SaveStudentInfo(student);

        return RedirectToAction(“Index”);

    }

    return View();

}

Step 12

Now, run your application and select the Edit button. Change the value and save it. the value will be updated.

Figure: Edit view of MVC Application before changing the value of StudentName and StudentClass 

Figure: Edit view of MVC Application after changing the value of StudentName and StudentClass 

Your application will appear like this when you’ve saved the changed value:

Figure: Output of MVC Application after Editing the value 

Conclusion

In this blog, we have seen how to Edit and Update a model. We can use it to update any record of the database and save the record of edited value.

Author Bio: Vinod Satapara – Technical Director, iFour Technolab Pvt. Ltd.Technocrat and entrepreneur of a reputed PowerPoint Addin Development Company with years of experience in building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using latest technologies and help organization to achieve goals.

By Anurag Rathod

Anurag Rathod is an Editor of Appclonescript.com, who is passionate for app-based startup solutions and on-demand business ideas. He believes in spreading tech trends. He is an avid reader and loves thinking out of the box to promote new technologies.