DotNetSlackers: ASP.NET News for lazy Developers

Showing posts with label mvc. Show all posts
Showing posts with label mvc. Show all posts

Friday, October 16, 2015

Repository Pattern with MVC and Entity Framework

In this tutorial We will learn How to create generic Repository Pattern with Asp.Net MVC and Entity Framework.

Repository Pattern is used to create an abstraction layer between data access layer and business logic layer of an application. This layer communicate with data access layer and provide data to business logic layer as per requirement.

In general Our controller action methods directly access the data context and get data from database.

Repository Pattern with Asp.Net MVC and Entity Framework
The main purpose of this Repository Pattern to Isolate the data access layer and business logic layer, so that Changes in any layer can not effect directly on other layer.

By using Repository Pattern, Our Controller Action Method won’t talk to Context Class Directly.

Now all the database action are done In our Repository.

Now wee will see how to create Generic Repository Pattern In Asp.Net Mvc and Entity Framework.

Create a MVC application.

Add Two Model class to your Model folder.

01
02
03
04
05
06
07
08
09
10
11
namespace RepositoryDemo.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Age { get; set; }
    }
}
?
1
2
3
4
5
6
7
8
using System.Data.Entity;
namespace RepositoryDemo.Models
{
    public class DemoContext:DbContext
    {
        public DbSet<Employee> employee { get; set; }
    }
}
Create GenericRepository folder in your project.
Repository Pattern with Asp.Net MVC and Entity Framework 

First Add an Interface to this folder

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
using System;
using System.Collections.Generic;
namespace RepositoryDemo.GenericRepository
{
    interface IRepository<T> where T:class
    {
        IEnumerable<T> getAll();
        T getById(object Id);
        void Insert(T obj);
        void Update(T obj);
        void Delete(Object Id);
        void Save();
    }
}
I have created generic IRepository interface, which contain method for all the CRUD Operations.
Similarly We will Create Generic Class which will implement IRepository Interface.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System.Collections.Generic;
using System.Linq;
using RepositoryDemo.Models;
using System.Data.Entity;
using System.Data;
using System;
namespace RepositoryDemo.GenericRepository 
{
    public class Repository<T>:IRepository<T> where T:class
    {
         
        private DemoContext demoContext;
        private DbSet<T> dbSet;
        public Repository()
        {
            this.demoContext = new DemoContext();
            dbSet = demoContext.Set<T>();
        }
        public IEnumerable<T> getAll()
        {
            return dbSet.ToList();
        }
        public T getById(object Id)
        {
            return dbSet.Find(Id);
        }
        public void Insert(T obj)
        {
            dbSet.Add(obj);
        }
        public void Update(T obj)
        {
             
            demoContext.Entry(obj).State = EntityState.Modified;
        }
        public void Delete(object Id)
        {
            T getObjById = dbSet.Find(Id);
            dbSet.Remove(getObjById);
        }
        public void Save()
        {
            demoContext.SaveChanges();
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.demoContext != null)
                {
                    this.demoContext.Dispose();
                    this.demoContext = null;
                }
            }
        }
    }
}

Our Generic Repository Pattern is Created.

Now We can use it in our Controller.
So create a Empty Home Controller to perform CRUD Operation using Repository Pattern over Employee class.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using System.Web.Mvc;
using RepositoryDemo.GenericRepository;
using RepositoryDemo.Models;
namespace RepositoryDemo.Controllers
{
    public class HomeController : Controller
    {
        private IRepository<Employee> _repository = null;
        public HomeController()
        {
            this._repository = new Repository<Employee>();
        }
        public ActionResult Index()
        {
            var employees = _repository.getAll();
            return View(employees);
        }
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(Employee employee)
        {
            if (ModelState.IsValid)
            {
                _repository.Insert(employee);
                _repository.Save();
                return RedirectToAction("Index");
            }
            else
            {
                return View(employee);
            }
        }
        public ActionResult Edit(int Id)
        {
            var employee = _repository.getById(Id);
            return View(employee);
        }
        [HttpPost]
        public ActionResult Edit(Employee employee)
        {
            if (ModelState.IsValid)
            {
                _repository.Update(employee);
                _repository.Save();
                return RedirectToAction("Index");
            }
            else
            {
                return View(employee);
            }
        }
        public ActionResult Details(int Id)
        {
            var employee = _repository.getById(Id);
            return View(employee);
        }
        public ActionResult Delete(int Id)
        {
            var employee = _repository.getById(Id);
            return View(employee);
        }
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int Id)
        {
            var employee = _repository.getById(Id);
            _repository.Delete(Id);
            _repository.Save();
            return RedirectToAction("Index");
        }
    }
}
I have declare IRepository as type of Employee.
Index View
Repository Pattern with Asp.Net MVC and Entity Framework
Details View
Repository Pattern with Asp.Net MVC and Entity Framework
Edit View
Repository Pattern with Asp.Net MVC and Entity Framework
Create New record
Repository Pattern with Asp.Net MVC and Entity Framework
Delete Record
Repository Pattern with Asp.Net MVC and Entity Framework
DOWNLOAD Code to get the View Code

Learn MongoDb with Asp.Net MVC


In this tutorial, I’ll show you how to use MongoDB with Asp.Net MVC.

Before start, Let’s know about MongoDB.

What is MongoDB ?

MongoDB is document oriented database, Where Records are stored as documents.
Is it also called as NOSQL database.
MongoDb stores the data in the form of document which is similar to JSON , Known as BSON.

BSON : BSON is a binary representation of JSON with additional type information.
Terms related to MongoDB.
  • Collection : A collection is a group of related documents that have a set of shared common indexes. Collections are analogous to a table in relational databases.
  • Documents : Document is set of Key-value pair. here is Document Sample
    ?
    1
    2
    3
    4
    {
    Name  : "Amit",
    Email : "amitverma0511@gmail.com"
    }
Advantage of using MongoDB.
  • A document-based data model. The basic unit of storage is analogous to JSON.
    This is a rich data structure capable of holding arrays and other documents.
  • No schema migrations. Since MongoDB is schema-free, your code defines your schema.
  • Replication is very easy.
  • You can perform rich queries.
  • More on MongoDB
Let’s get started
First of all Download the MongoDB.
How to Install MongoDB.
After installing MongoDb in your system .

Create Database in MongoDb.

Here I’m creating Database name as “School“.
Execute the following command in Mongo Shell.

1
use School
Learn MongoDb with Asp.Net MVC

Insert records in School Database .

Create an array which contains list of name of student.
using for loop we will insert records.

1
2
3
4
var Name=["Amit","Rohit","Ajay","Sumit","Rahul"];
 for(i=0 ;i<5;i++){
    db.Students.insert({Name : Name[i]});
}
Learn MongoDb with Asp.Net MVC
Now you see the inserted records by using following query.

1
db.Students.find()
Learn MongoDb with Asp.Net MVC
So far we have created Database and Inserted records in it.
Now let’s learn how to connect MongoDb with C#.

Download C# Driver for MongoDB

Extract the Zip file (if you have downloaded the .Zip file)

In Extracted folder, you will get two .dll file
  • MongoDB.Bson.dll
  • MongoDB.Driver.dll
Now create an Asp.Net MVC project.
Add the the reference of those two dll file.
Right click on Reference => Add Reference => Browse
Learn MongoDb with Asp.Net MVC
Add a Model Class Students.
?
01
02
03
04
05
06
07
08
09
10
11
using MongoDB.Bson;
 
namespace MvcWithMongoDb.Models
{
    public class Students
    {
 
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
}
Add Home Controller .
Create constructor of HomeController.

01
02
03
04
05
06
07
08
09
10
11
12
13
private MongoDatabase mongoDatabase;
public HomeController()
{
    // create connectionstring
    var connect = "mongodb://localhost";
    var Client = new MongoClient(connect);
 
    // get Reference of server
    var Server = Client.GetServer();
 
    // get Reference of Database
    mongoDatabase = Server.GetDatabase("School");
}
In Constructor, I have created Mongo Client which need the connection string.
Mongo Client will interact with the server, so using MongoClient instance , call the GetServer method.
Now to Access the database of MongoDb, I have used this instance of Server.
Now Create Method which will return Json Type result.
?
01
02
03
04
05
06
07
08
09
10
11
public JsonResult GetAll()
{
    var collections = mongoDatabase.GetCollection<Students>("Students");
    IList<Students> students = new List<Students>();
    var getStudents = collections.FindAs(typeof(Students), Query.NE("Name", "null"));
    foreach (Students student in getStudents)
    {
          students.Add(student);
    }
    return Json(students, JsonRequestBehavior.AllowGet);
}
Complete code for controller.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System.Collections.Generic;
using System.Web.Mvc;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MvcWithMongoDb.Models;
namespace MvcWithMongoDb.Controllers
{
    public class HomeController : Controller
    {
        private MongoDatabase mongoDatabase;
        public HomeController()
        {
            // create connectionstring
            var connect = "mongodb://localhost";
            var Client = new MongoClient(connect);
 
            // get Reference of server
            var Server = Client.GetServer();
 
            // get Reference of Database
            mongoDatabase = Server.GetDatabase("School");
        }
 
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetAll()
        {
            var collections = mongoDatabase.GetCollection<Students>("Students");
            IList<Students> students = new List<Students>();
            var getStudents = collections.FindAs(typeof(Students), Query.NE("Name", "null"));
            foreach (Students student in getStudents)
            {
                  students.Add(student);
            }
            return Json(students, JsonRequestBehavior.AllowGet);
        }
    }
}
Add the Index view .
write the following code.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Script/jquery-2.1.1.min.js"></script>
<script src="~/Script/School.js"></script>
<div id="divList">
    <p>
        <img src="~/Content/images/images.jpg" />
    </p>
    <table class="table table-bordered" id="tblList">
        <tr>
            <th colspan="2" style="text-align:center;">Student List</th>
        </tr>
        <tr>
            <th> SNo.</th>
            <th>Name</th>
        </tr>
    </table>
</div>
You can see, I have added Js file named “School.js”.
write the following code in School.js.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
$(document).ready(function () {
    GetAll();
});
 
function GetAll()
{
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        url: 'Home/GetAll',
        success: function (data) {
            var genHtml = "";
            $.each(data, function (index, value) {
                genHtml += "<tr><td>"+(index+1)+"</td><td>" + value.Name +"</td></tr>";
            });
            $('#tblList').append(genHtml);
        },
        error: function (data) {
            alert('Error in getting result');
        }
    });
}
See the Result.
Demo
Learn MongoDb with Asp.Net MVC
DOWNLOAD

Tuesday, October 13, 2015

What is AJAX Helpers in ASP.NET MVC

Ajax helper in ASP.NET MVC essentially provides Ajax functionality for your web applications. AJAX Helpers are used for creating AJAX enabled elements for example Ajax enabled forms and links which performs request asynchronously. when you use Ajax helper you can submit your HTML form using Ajax so that instead of refreshing the full web page only a part of it can be refreshed. you can render action links that allow you invoking action methods using Ajax. Basically AJAX Helpers are extension methods of AJAX Helper class which exists in System.Web.Mvc.Ajax namespace.

AJAX-enabled link based example:-

Here I have created a example to show how to use AJAX action link using action and controller in Asp.Net MVC.

@Ajax.ActionLink("Fatch Data""GetData"new AjaxOptions {UpdateTargetId = "Data-container", HttpMethod = "GET" })


Unobtrusive AJAX in MVC?

Unobtrusive Validation and AJAX support in  MVC follows  best practices that enable Progressive Enhancement and also easy to use. The unobtrusive AJAX library (not the unobtrusive validation library) is admittedly a bit limited in functionality, but if it fulfill the requirements of the application you are writing, then by all means use it. And because the source code of it is in your app (it's JavaScript, after all), it's generally straightforward to make any updates or changes to it as you see fit.
Configuration options for AJAX Helpers
 It is very important to know the AjaxOptions class defines properties that allow you to specify callbacks for different stages in the AJAX request life cycle. There are several properties in AjaxOptions. Now You can use these property as par different scenario and different requirements. There are following properties provided by AjaxOptions class for AJAX helpers:

Url : Specify the URL that will be requested from the server.

Confirm: Specify a message that will be displayed in a confirm dialog to the end user.When user
clicks on OK button in the confirmation dialog, the Ajax call performs.

OnBegin: Specify a JavaScript function name which is called at the beginning of the Ajax request.

OnComplete: Specify a JavaScript function name which is called at the end of the Ajax request.

OnSuccess:  Specify a JavaScript function name which is called when the Ajax request is successful.

OnFailure:  Specify a JavaScript function name which is called if the Ajax request fails.

LoadingElement:  Specify progress message container’s Id to display a progress message or animation to the end user while an Ajax request is being made.

LoadingElementDuration: Specify a time duration in milliseconds that controls the duration of the progress message or animation.

UpdateTargetId: Specify the target container’s Id that will be populated with the HTML returned by the
action method.
InsertionMode: Specify the way of populating the target container. The possible values are InsertAfter, InsertBefore and Replace (which is the default).

Cross Domain AJAX (CORS)?
Cross-domain requests require mutual consent between the Web page and the server. You can initiate a cross-domain request in your Web page by creating an XDomainRequest object off the window object and opening a connection to a particular domain. The browser will request data from the domain's server by sending an Origin header with the value of the origin. It will only complete the connection if the server responds with an Access-Control-Allow-Origin header of either * or the exact URL of the requesting page. By default in ASP.NET MVC, any web browsers allows AJAX calls only to our web application’s site of origin. This will allow us to prevent various security issues. In that case, you have two options: Either add CORS header "Access-Control-Allow-Origin: *" to the response (and configure the client ajax() call with dataType:"html"), or create a special JSON(P) page that delivers the same data as JSON (with padding) (and configure the client ajax() call like in the OP, with dataType:"jsonp").