+91-90427 10472
         
Dot net training in Chennai -Maria Academy

Consume WCF application in MVC

26 Oct 2016

Document by Ganesan – Ganesanva@hotmail.com – + 919600370429

Create a new MVC application.
Create Connection string in Web.config as below.

<connectionStrings>
<add name=”TestConnection” connectionString=”Data Source=(LocalDb)\v11.0;Initial Catalog=TestDB;Integrated Security=True;Pooling=False” providerName=”System.Data.SqlClient” />
</connectionStrings>

Create StudentDetails.cs Class file as below.

[DataContract]
public class StudentDetails
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string StudentName { get; set; }
[DataMember]
public int? Age { get; set; }
}

Create DBContext.Cs file as below

public class UsersContext : DbContext
{
public UsersContext()
: base(“TestConnection”)
{
}
public DbSet<StudentDetails> studentDbset { get; set; }
}

Create ScafFolding and autogenerate Views and controllers.
Make sure the Code now works in DB first approach. After this we are going to change the
data source to consume From WCF.
Create Service Reference as below,


Click OK. Now the service reference will be added as below,

Replace the Controller methods for CRUD as below,

public ActionResult Index()
{
SampleMVC1.ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client();
List<SampleMVC1.ServiceReference1.StudentDetails> objStudentDetails= objService.GetStudentData();
return View(objStudentDetails);
}
[HttpPost]
public ActionResult Create(SampleMVC1.ServiceReference1.StudentDetails studentdetails)
{
if (ModelState.IsValid)
{
SampleMVC1.ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client();
string result= objService.CreateStudentData(studentdetails);
return RedirectToAction(“Index”);
}
return View(studentdetails);
}
//
// GET: /Student/Edit/5
public ActionResult Edit(int id = 0)
{
SampleMVC1.ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client();
SampleMVC1.ServiceReference1.StudentDetails studentdetails = objService.GetStudentDatabyID(id);
if (studentdetails == null)
{
return HttpNotFound();
}
return View(studentdetails);
}
//
// POST: /Student/Edit/5
[HttpPost]
public ActionResult Edit(SampleMVC1.ServiceReference1.StudentDetails studentdetails)
{
if (ModelState.IsValid)
{
SampleMVC1.ServiceReference1.Service1Client objService = new ServiceReference1.Service1Client();
string result = objService.UpdateStudentData(studentdetails);
return RedirectToAction(“Index”);
}
return View(studentdetails);
}

Replace the view First line I.E model reference to point to Service model

Similar for other pages too.


Now the pages will be like below



Click on the Link below to get the sample solution
https://1drv.ms/u/s!ArddhCoxftkQg6gdCJeDrlqBAJE0vg

Social tagging: > > > > > > > > > >