-->

Monday, April 20, 2015

Creating a Model in Asp.Net MVC

Creating a Model means create a database table with required fields in form of simple class and its properties. This class must be added to the pre-added folder Models which differentiate this from all the simple classes in the MVC application.
In earlier article we have created a view for an existing action method Index which is by default added. At the same time we have passed some values from the same action to the respective view page. Those values have been passed through ViewBag, used to dynamically share values from controller to view.
Models folder contains all the classes used to represent application model for the application including validation logic and data access. Right click on the Models folder and add a new class Product and add some properties in that class as shown below:
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
public string Description {get; set;}
public string Color {get; set;}
public string Type {get; set;}
public double Price {get; set;}
}
Using this model class we can either create a database through code- first approach or just use it with a List object to show the data on view page. We will use second option here, create a simple list object and pass items to view page.
Create a Controller ProductsController and choose Empty MVC Controller in Template selection. There is a default action method Index, delete and create a new action method List. You can even change its name from Index to List because there is not view page for this action method.
In this action method we will create a simple list of products with some items and then show those items in the list page. Write the below code in this list method:
public ActionResult List()
{
List<Product> productList = new List<Product>();
productList.Add(new Product() { Id = 1, Name = "Mouse", Color = "Black", Description = "", Price = 800, Type = "Electronics" });
productList.Add(new Product() { Id = 2, Name = "Scanner", Color = "White", Description = "", Price = 3000, Type = "Electronics" });
productList.Add(new Product() { Id = 3, Name = "Mobile", Color = "Dark Grey", Description = "", Price = 6000, Type = "Electronics" });
productList.Add(new Product() { Id = 4, Name = "Shirt", Color = "Blue", Description = "", Price = 850, Type = "Cloths" });
productList.Add(new Product() { Id = 5, Name = "Shampoo", Color = "Black", Description = "", Price = 125, Type = "Hair Product" });

return View(productList);
}
Create a View for this action method which will have the same name “List”. In this view file we have to write simple html that will show all the records added in the action method. Write the below code in this view page:
@model IEnumerable<CodeWallMVCApplication.Models.Product>
@{
ViewBag.Title = "List";
}

<h2>Product List</h2>

<table>
<thead>
<tr>
<th>No.</th>
<th>Name</th>
<th>Description</th>
<th>Color</th>
<th>Type</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Description</td>
<td>@item.Color</td>
<td>@item.Type</td>
<td>@item.Price</td>
</tr>
}
</tbody>
</table>
The first line specifies about the model rendered on this view, remaining code is same as simple html code. Run this application the on the address bar write http://localhost:53420/Products/List and it will show the product list, added on the action method. In the address, port no may be change according to the application created so don’t copy it from here, just run your application.
Creating a Model in Asp.Net MVC

Creating a View in Asp.Net MVC

Creating a View means adding an HTML file for an existing action method in controller. View is the page that is shown to user, whatever HTML you write or CSS you embed is fully applicable for that view.
In earlier article we have created a controller having an “Index” action method which is by default added. We have changed this action method and returns a string to be displayed on browser directly.
When working with views programmer should know about HTML language and should have a little bit knowledge of CSS style-sheets. In this article we will create a view page checking the options that can be applied on creating a view.
Change index action method as it was when created:
public ActionResult Index()
{
return View();
}
Right click on Index and click on Add View. It will show Add View dialog box having a list of options as in below screenshot. We will discuss all these options in later articles, by now just click on Add button.
Right click on Index and click on Add View

Expand the Views folder, it have a new folder having the same name of our controller i.e. Home. All the views created through this controller will be saved in this folder. Open the newly created view, it have only a bit code as shown:
Open the newly created view

Change this code and insert an hyperlink <a href="www.codewalls.com">Code Walls</a>. Run this project and it will default show this page.
Change this code and insert an hyperlink

 
Data on View from Controller
When we create an MVC application as “Internet Application” template then by default Index action method have a Viewbag message defined as shown below:
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

return View();
}
Change this message or leave as is (I have changes this message a little bit) and in the view page there is a line showing the output of this viewbag message i.e.
@ViewBag.Message
Run this project and check the message on the page as shown in green ellipse. You can change this in-built template according to your own design scenario. Using ViewBag you can dynamically share the values from controller to view, we will discuss more about it later.
Creating a View in Asp.Net MVC


Friday, April 10, 2015

Creating a Controller in Asp.Net MVC

What is the MVC architecture and how it can be used to build a web application has been discussed in our earlier article. We will discuss about the concept of MVC in context of classes that can be easily accessible in our application. These classes can be created as simply as other classes including properties to be get/set values. MVC stands for Model, View and Controller that divides a web application into three parts. These parts are data, user-interfaces and logics which differentiates everything about an application. Here is a one-line definition about MVC:
  • Model: these are the classes representing your application data including the properties your database have.
  • View: a simple page that will show to user and redirect your complex code into basic HTML. Decides the design in which data will show.
  • Controller: these classes are responsible for what is to be shown in which view.
In earlier article, we have created a simple internet application having all the basic folders and packages. Those folders contains App_Start, Content, Controllers, Scripts, Models and of course Views. Now I am starting with an Empty MVC application having only some of these folders and don’t have any code logics. Just right click on Controllers and select Add--> Controller, "Add Controller" window will appear with options listed below:


Controller in MVC


Specify the name “Home” and set Template as “Empty MVC controller” and click on add button will add a “HomeController” under Controllers folder. This controller have only one action “Index” having the structure below:

Controller code view in MVC


Look out the default code, there is only one action added i.e. “Index” having the return type “ActionResult” which is commonly preferred by all the action methods. Basically this action method is used for default view about any controller like listing or home page. Suppose there is a controller for products then the index action will show all the products having functionality like add/edit/delete. Now change this action a little bit as shown:
public class HomeController : Controller 
public string Index() 
{ return "This is my first controller"; } 
}
Run this application and it will show the string returned by the above “Index” method.


output:Creating a Controller in Asp.Net MVC


Check out the address in browser, there is only “localhost:portNo” without any controller’s name. This is because the default routing of an MVC application is Controller: Home and Action: Index. That’s why it is showing only the port number of the application.

How to retrieve data from two tables in MVC

Introduction

In this article, i want to bind  hyperlink from one database table like department and when we click on any department name then we will get all employee name, which is stored in second database table. In my previous example, we have to learn how to retrieve data from single database table also learn how-to bind hyperlink in mvc. Today, we will take help of both articles and learn how to retrieve data from two tables in mvc. First to prepare department class with some data members also mapped this with department table, this is already mentioned in previous post. Also add employee class in it.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace WebApplication11.Models
{
[Table("Department")]
public class Department
{
public int Id { get; set; }
public string Name { get; set; }

public List<Employee> Employee { get; set; }
}
}

Create DepartmentContext class for retrieving department data from the database  table. If you are use same context for multiple table, MVC 5  generate error.


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

namespace WebApplication11.Models
{
public class DepartmentContext : DbContext
{
public DepartmentContext()
: base("EmployeeConnection")
{ }
public DbSet<Department> Departs { get; set; }
}
}

Here, connection string save in web.config file. Through Departs property i will get all records from the database table. Now, we create a controller class and view for controller class. In which, i will get all the records from department table using List collection and these items render on the browser using View.


public class DepartmentController : Controller
{
//
// GET: /Department/
public ActionResult Index()
{
DepartmentContext context = new DepartmentContext();
List<Department> dept = context.Departs.ToList();
return View(dept);
}
}

Get the list of department using context instance. Render by the view, so check the view, which is prepare for Department


@model IEnumerable<WebApplication11.Models.Department>
@using WebApplication11.Models;
@{
ViewBag.Title = "Index";
}

<h2>Index</h2>
<ul>
@foreach(Department dt in @Model)
{
<li>@Html.ActionLink(dt.Name,"Index1","Employee",new{DepartmentId=dt.Id},null)</li>
}
</ul>

The Action link method contains some parameters, which are name of the department,  calling method, name of the controller where your method exist and last one is parameter which is pass in the method.  Now, prepare the employee class and EmployeeContext in model folder.


namespace WebApplication11.Models
{
[Table("Employee")]
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int DeptId { get; set; }
}
}

How to retrieve data from two tables in MVC


Similarly again, Create a Context for employee class, In which we can retrieve the data from employee table.

namespace WebApplication11.Models
{
public class EmployeeContext:DbContext
{
public EmployeeContext()
: base("EmployeeConnection")
{

}
public DbSet<Employee> Employees { get; set; }

}
}

Now, create a controller and view for employee class. In which we can create a single method that is Index1 and retrieve the employee information whos department id is selected.


public class EmployeeController : Controller
{
//
// GET: /Employee/
public ActionResult Index1()
{
EmployeeContext context = new EmployeeContext();
Employee emp = context.Employees.Single(emp1 => emp1.DeptId == 1);
return View(emp);
}
}

And create the view for employee.

@model WebApplication11.Models.Employee

@{
ViewBag.Title = "Index1";
}

<h2>Index1</h2>
<p>@Model.Name</p>

Code generate the following output

How to retrieve data from two tables in MVC

fix parameters dictionary contains a null entry

Introduction

Basically that's type of error occurs due to null value. But i have already try to pass some value, manually in the controller function. Always i get this error. Ok let's start to story of the error. I want to get the record from single department table and that's name is hyperlinked. Now, When i click to any hyperlink then open respective employee details, which is stored in another table. What i was done. First i was write the code for retrieving the value from single data base table, on that time, my code run successfully. But in Next time when i wrote the code for retrieving the record from two database table, on that time, i got the error.

What steps i have taken

  1. First step to prepare classes for employee and department
  2. Second step to create a context for both class
  3. third step to prepare a controller for department, as well as prepare view for department
  4. forth step to prepare controller for employee, as well as prepare view for employee.

Error

The parameters dictionary contains a null entry for parameter 'deptid' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult linkEmp(Int32)' in 'WebApplication10.Controllers.EmployeeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters.

SnapShot


How to fix it

Prepare the seperate Context class for each model. I have two class that is employee and department , If you want to retrieve data from both class then you want to make two seperate context for each. I have two context that is 1. EmployeeContext 2. DepartmentContext

Thursday, April 9, 2015

Access data from database table in MVC

In MVC, we can access data from database easily. When we send any request to the server, respond generated by the controller. Data access from the Model and render by the View. First to make a database table using visual studio 2010 or higher. we have database table that is "Employee", in which have some attributes, these are

CREATE TABLE [dbo].[Employee]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[Name] NVARCHAR(50) NULL,
[Age] INT NULL
)


  1. First to install entity framework by the "Nuget packages", which is available in tools-->Library Package Manager
  2. This is already available in 4.5 framework or 4.5.1.
ntity framework by the "Nuget packages
  1. Now, add the employee class in model folder with some public properties  like
  2.  
     namespace WebApplication10.Models
    {
    public class Employee
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public int age { get; set; }
    }
    }
    
    
  3. Now, add another class which is EmployeeContext.cs class, which is inherit from DBContext class. DBContext class is available in System.Data.Entity namespace. This class is used for making connection. Now, your code look like
  4.  
    using System.Data.Entity;namespace WebApplication10.Models
    {
    public class EmployeeContext: DbContext
    {
    public DbSet<Employee> empl { get; set; }}
    }
    
    Here, empl is the public property, by which we can create the connection to the database.
  5. Now, add the ConnectionString in the web.config file that is
    <add name="EmployeeConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Initial Catalog=Database1;Integrated Security=True"
    providerName="System.Data.SqlClient" />
    
    
  6. Map the database table with the Employee class using Table class which is available in  System.ComponentModel.DataAnnotations.Schema; namespace, after mapping now your code look like
    using System.ComponentModel.DataAnnotations.Schema;namespace WebApplication10.Models
    {[Table("Employee")]
    public class Employee
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public int age { get; set; }
    }
    }
    
  7. Now, create a EmployeeController  in controller folder, Which is inherit from Controller class. This Controller class is exists in System.Web.Mvc namespace. Also create a public method, which return ActionResult class. Now your code look like
     using System.Linq;
    using System.Web.Mvc;
    using WebApplication10.Models;
    
    namespace WebApplication10.Controllers
    {
    public class EmployeeController : Controller
    {
    //
    // GET: /Employee/
    public ActionResult Index()
    {
    EmployeeContext context = new EmployeeContext();
    Employee emp = context.pl.Single();
    
    return View(emp);
    }
    }
    }
    
    Here we create a instance of EmployeeContext class and invoke the public property of that class.
  8. Now create the view for this program. Before adding the view with their presentation must build the project. Learn How to create the new view
 create the view for this program

  1. Prepare the view and access all the properties of the employee class by the @Model properties.
     @model WebApplication10.Models.Employee
    
    @{
    ViewBag.Title = "Employee Details";
    }
    
    <h2>Employee Details are:</h2>
    Employee Id : <p>@Model.ID</p>
    Employee Name : <p>@Model.Name</p>
    Employee Age : <p>@Model.age</p>
    
    
  2. Now run the code and check your desired output
Access data from database table in MVC

Data Binding in MVC

In MVC, we can access data from database easily. When we send any request to the server, respond generated by the controller. Data access from the Model and render by the View. First to make a database table using visual studio 2010 or higher. we have database table that is "Employee", in which have some attributes, these are
CREATE TABLE [dbo].[Employee]
(
[Id] INT NOT NULL PRIMARY KEY IDENTITY,
[Name] NVARCHAR(50) NULL,
[Age] INT NULL
)
  1. First to install entity framework by the "Nuget packages", which is available in tools-->Library Package Manager
  2. This is already available in 4.5 framework or 4.5.1.
  3. Install Entity Framework By the nuget packages
  4. Now, add the employee class in model folder with some public properties  like
     namespace WebApplication10.Models
    {
    public class Employee
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public int age { get; set; }
    }
    }
    
    
  5. Now, add another class which is EmployeeContext.cs class, which is inherit from DBContext class. DBContext class is available in System.Data.Entity namespace. This class is used for making connection. Now, your code look like
    using System.Data.Entity;namespace WebApplication10.Models
    {
    public class EmployeeContext: DbContext
    {
    public DbSet<Employee> empl { get; set; }}
    }
    
    Here, empl is the public property, by which we can create the connection to the database.
  6. Now, add the ConnectionString in the web.config file that is
    <add name="EmployeeConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Initial Catalog=Database1;Integrated Security=True"
    providerName="System.Data.SqlClient" />
    
    
  7. Map the database table with the Employee class using Table class which is available in  System.ComponentModel.DataAnnotations.Schema; namespace, after mapping now your code look like
    using System.ComponentModel.DataAnnotations.Schema;namespace WebApplication10.Models
    {[Table("Employee")]
    public class Employee
    {
    public int ID { get; set; }
    public string Name { get; set; }
    public int age { get; set; }
    }
    }
    
  8. Now, create a EmployeeController  in controller folder, Which is inherit from Controller class. This Controller class is exists in System.Web.Mvc namespace. Also create a public method, which return ActionResult class. Now your code look like
     using System.Linq;
    using System.Web.Mvc;
    using WebApplication10.Models;
    
    namespace WebApplication10.Controllers
    {
    public class EmployeeController : Controller
    {
    //
    // GET: /Employee/
    public ActionResult Index()
    {
    EmployeeContext context = new EmployeeContext();
    Employee emp = context.pl.Single();
    
    return View(emp);
    }
    }
    }
    
    Here we create a instance of EmployeeContext class and invoke the public property of that class.
  9. Now create the view for this program. Before adding the view with their presentation must build the project. Learn How to create the new view

Before adding the view with their presentation must build the project


  1. Prepare the view and access all the properties of the employee class by the @Model properties.
     @model WebApplication10.Models.Employee
    
    @{
    ViewBag.Title = "Employee Details";
    }
    
    <h2>Employee Details are:</h2>
    Employee Id : <p>@Model.ID</p>
    Employee Name : <p>@Model.Name</p>
    Employee Age : <p>@Model.age</p>
    
    
  2. Now run the code and check your desired output

Data Binding in MVC

© Copyright 2013 Computer Programming | All Right Reserved