Friday, 6 December 2013

Genarating Radiobuttonlist Control in MVC 4

Here i am going to explain generate a radiobuttonlist in mvc. In previous articles i am explained code first approach,before seeing this article please see that article,you will get better idea on how to enable migrations,and how to craete data context class.click here to go that article. For this Create Two Model Classes one is Department and another one is Company.

 public class Department
    {
        [Key]
        public int DeptId { get; set; }
        public string DeptName { get; set; }
    }


Create company Model class and write the following code

public class Company
    {
        public string SelectDepartment { get; set; }

        public List<Department> departments
        {
            get
            {
                DataContext db = new DataContext();
                return db.department.ToList();
            }
        }

    }


In above code DataContext class is in Models folder..(to know about datacontext class and furthur details click here)

datacontext class
public class DataContext:DbContext
    {
        public DataContext() : base("EmployeeDb")
        {
        }
        public DbSet<Employee> employee { get; set; }

        public DbSet<Department> department { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
            modelBuilder.Entity<Employee>().ToTable("employee");
            modelBuilder.Entity<Department>().ToTable("department");
     }

 we have to include department class in datacontext class..if we change model class the database table will be changed for that we have to write onmodelcreating method.




Now go to Home controller and write one action method name it as Radio and write the following code

 public ActionResult Radio()
        {
            Company comapny = new Company();
            return View(comapny);
        }


right click on radio and add view to action method



now write radiobutton control in form and write the following code

@model MvcEmployee.Models.Company

@{
    ViewBag.Title = "Radio";
}

<h2>Radio</h2>
@using (Html.BeginForm())
{
    foreach(var dept in Model.departments)
    {
       @Html.RadioButtonFor(m=>m.SelectDepartment,dept.DeptId)@dept.DeptName
  

  <br />
 }   
     
    <input type="submit" value="Submit" />
}







Now go to Home Controller write the HttpPost method for Radio Action method

  [HttpPost]
        public string  Radio(Company company)
        {
            if (string.IsNullOrEmpty(company.SelectDepartment))
            {
                return "You did not select any department";
            }
            else
                return "You selected department with Id " + company.SelectDepartment;

        }






Now run the application and you see the following output









 If you didn't select any department and click on submit it shows "You did not select any department".
If you select Finance department and click on submit  it shows "You selected department with Id 3"


tags:radiobuttonlist in mvc 3,radiobuttonlist in mvc ,radiobuttonlist in mvc 4,radiobuttonlist in mvc 5,generate radiobuttonlist in mvc,radiobuttonlist and getting the values from data base,how to create radiobutton in mvc 4 razor,radiobutton in mvc razor,radiobutton list asp.net mvc 4

Thursday, 5 December 2013

DropDownList in MVC 4


Here I am going to explain the generating drop downl ist and get the values from database table. First of all create one Model class named as Department. This example is explained in code first approach .For this follow the below procedure .In previous articles i am explained code first approach,before seeing this article please see that article,you will get better idea on how to enable migrations,and how to craete data context class.click here to go that article.
To open vs 2010 and to create new project and for code first approach click here

 Directly i am going to Model's folder and add department Model class




public class Department
    {   [Key]
        public int Id { get; set; }
        public string Name { get; set;}
    }















 Change the DataContext class(how to create datacontext clas click here)

include the department model class in datacontext class

 add namespace using MvcEmployee.Migrations;
public class DataContext:DbContext
    {
        public DataContext() : base("EmployeeDb")
        {
        }
        public DbSet<Employee> employee { get; set; }

        public DbSet<Department> department { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

            base.OnModelCreating(modelBuilder);
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>());
            modelBuilder.Entity<Employee>().ToTable("employee");
            modelBuilder.Entity<Department>().ToTable("department");
     }

    }






 Now go to Home Controller and write action method name it as Dept and write the following code.

create the instance for DataContext class

Add namespace using MvcEmployee.Models;

private DataContext db = new DataContext();

public ActionResult Dept()
        {
            ViewBag.Departments = new SelectList(db.department, "DeptId", "DeptName");
            return View();
        }

Add view to Dept Action method and write the following in Dept.cshtml

 @Html.DropDownList("Departments", "Select Department")



The Departments should be same as Viewbag attribute name in home controller


Now run the application and you see the following output
 There is no records in the Dropdownlist.Now go to database insert few records in department table.(If the table has records ,those are loaded into dropdownlist.)

Now run the application see the following output


tags:dropdownlist in mvc ,dropdownlist in mvc 3,dropdownlist in mvc 4,dropdownlist in mvc razor,dropdownlist in mvc get the values from database,dropdownlist in asp.net mvc, dropdownlist in asp.net mvc 5,generate dropdownlist in asp.net mvc,how to create dropdownlist in mvc 4,how to create dropdownlist in mvc5



Friday, 22 November 2013

Create Wcf Service using Entity Framework

In this article i am going to explain CRUD operations in WCF services using Entity Framework.First create one Customer Table in database.Now i want to get all the customers data from database for this i implemented one method called GetCustomers like this i implemented different methods for inserting data into database table,Update data into  Customers table and deleting customers.

Create Customer table in Database

In customer table fields are CustomerId,CustomerName,Address,Email.
Now go to Visual Studio . Follow this path ,File=>New=>Project =>WcfServiceApplication and name it as CustomerServices and click OK


Go to Iservice1.cs file and write the following code in Iservice1 interface
  [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
        [OperationContract]
        List<Customer> GetCustomers();
        [OperationContract]
        bool InsertCustomer(Customer obj);     
        [OperationContract]
        bool UpdateCustomer(Customer obj);
        [OperationContract]
        bool DeleteCustomer(int cid);
    }

write another class named as Customer  in Iservice1.cs
[DataContract]
    public class Customer
    {
        [DataMember]
        public int CustomerId { get; set; }
        [DataMember]
        public string CustomerName { get; set; }
        [DataMember]
        public string Address { get; set; }
        [DataMember]
        public string Email { get; set; }
    }



Right click on the ‘CustomerServices’ project in Solution Explorer > Add > New Item. Select the Data Template > ADO.NET Entity Data Model and click Add.

 Now select Generate from database and click on Next




click on New Connection



 Write the server name with in textbox .if you are using Sql Server Authentication then fill username and password, and select database which you are using. click on OK.
 Now you get the following screen ,check the check box having  Yes,include the sensitive data in connection string. Now click on Next




Now select customer table and click on finish. you get the following entity model

 Now change the Customer name to CustomerEntity because the project has already one Customer class in Iservice1.cs file.
To change class name right click on Customer and click on Rename and change it to CustomerEntity


Now go to Service1.svc.cs file and write the method for Getting customers data from database

public List<Customer> GetCustomers()
        {
             Customer customer=null;
            List<Customer> lstcust = new List<Customer>();
            using(var context=new RaviEntities())
            {
                var customerEntity = (from cust in context.CustomerEntities select cust).ToList();
                if (customerEntity != null)
                    foreach (var cust in customerEntity)
                    {
                        customer = new Customer();
                        customer.CustomerId = cust.CustomerId;
                        customer.CustomerName = cust.CustomerName;
                        customer.Address = cust.Address;
                        customer.Email = cust.Email;
                        lstcust.Add(customer);
                    }
            }       
            return lstcust;
        }

Implement the method for inserting data into customer table

 public bool InsertCustomer(Customer obj)
        {
            CustomerEntity objcust = new CustomerEntity()
            {
                CustomerId = obj.CustomerId,
                CustomerName = obj.CustomerName,
                Address = obj.Address,
                Email = obj.Email
            };
            RaviEntities db = new RaviEntities();
            db.CustomerEntities.AddObject(objcust);
            // db.AddToCustomerEntities(objcust);
            db.SaveChanges();
            return true;
        }





 Implement the method for update data into customer table
   public bool UpdateCustomer(Customer obj)
        {
            var custId = obj.CustomerId;
            using (RaviEntities context = new RaviEntities())
            {
                var customerEntity = (from c in context.CustomerEntities where c.CustomerId == custId select c).Single();
                if (customerEntity != null)
                {
                    customerEntity.CustomerId = obj.CustomerId;
                    customerEntity.CustomerName = obj.CustomerName;
                    customerEntity.Address = obj.Address;
                    customerEntity.Email = obj.Email;
                    context.CustomerEntities.DeleteObject(customerEntity);
                    context.SaveChanges();
                    context.AddToCustomerEntities(customerEntity);
                    context.SaveChanges();
                }
            }

            return true;
        }


Implementing Method for Deleting the customer


  public bool DeleteCustomer(int cid)
        {
            using (RaviEntities context = new RaviEntities())
            {
                var customerEntity = (from c in context.CustomerEntities where c.CustomerId == cid select c).Single();
                if (customerEntity != null)
                {
                    context.CustomerEntities.DeleteObject(customerEntity);
                    context.SaveChanges();           
                }
            } 
            return true;
        }



Now  run the application and copy the url
http://localhost:3970/Service1.svc 

Check wcf services are working are not

How to check Wcf Services  :


Go to  Visual Studio Command Prompt and type wcftestclient and click Enter key. Now it opens another window


Now click on addservice and paste that url and click OK. you get the all methods in the services

For Getting All Customers ..double click on the method.=>Click on Invoke=> Select Ok
Now you get the following output



Similarly you can check all the methods like this.