Saturday, 28 November 2015

Static RadiobuttonList in AngularJs

This  article will teach you the basics of Radiobutton list list in AngularJs with Asp.Net Mvc Application.Yo can use Microsoft Visual studio to follow this article.
Create a Sample Asp.Net Mvc application name it as AngularRadioButtonList.the project architecture doesn’t contain any angularjs scripts, so we need to add angularjs scripts from Nuget Packages.

Right click on project “AngularRadioButtonList”=>  select Manage Nuget Package=> on  top right search as angularjs ,you will get Angularjs related frameworks now select Angularjs and click on install.Now angularjs scripts successfully added your scripts Folder.

Angularjs doesn’t have directives to build radiobuttions like ng-options use to build select list.
Now create one mvc controller name it as radio and add one action method index


Add view to inde action method,now include following script from the scripts folder
<script src="~/Scripts/angular.min.js"></script>


See the below example
<script src="~/Scripts/angular.min.js"></script>
<script>
    angular.module('radioExample', [])
      .controller('ExampleController', ['$scope', function ($scope) {
      }]);
</script>

<form name="myForm" ng-app="radioExample">
    <div ng-controller="ExampleController">
        <label>
            <input type="radio" ng-model="country.name" value="India">
            India
        </label><br />
        <label>
            <input type="radio" ng-model="country.name" value="USA">
            USA
        </label><br />
        <label>
            <input type="radio" ng-model="country.name" value="China">
            China
        </label><br />
        <h3>Country = {{country.name | json}}</h3><br />
    </div>
</form>
                             
In the above example we need to include ng-app and ng-controller because ng-app is used to initialize angularjs application,the ng-app directive should be initialzed at root element of the application ,its not mandatory.
ng-controller is a javascript function,it prepares  the model for view. The ng-controller attaches model to the scope.
Radio button in angularjs  has the following aruments.
ngModel,value,ngname, ngchange , ngValue

ngModel : it is a assignable angular expression ,we can assign dynamic data

value: whenever we select ngModel that value will be set to this value 
parameter. value supports only string values.

ngchange: this is like  radiobutton event ,it will execute when input changes

name:it is property name of the form.

ngValue: when radio button is selected ng-model value will be set to this ng-value.we can use it instead of value parameter.

Apart from now select the radio button it will display the selected radiobutton value.
Lets see the output


Tags:Radiobuton list in angularjs ,static radiobuttonlist in angularjs,dynamic radiobuttonlist  in angularjs,radiobuttonlist,angularjs radiobuttonlist ,mvc angularjs radiobutton,radiobuttonlist in angularjs, mvc radiobuton list in angularjs, radiobuttonlist  in angularjs from database


Saturday, 1 August 2015

Web Api CRUD Operations without Repository Using Entity Framework

CRUD stands for Create ,Read, Update and Delete, these are four basic standard database operations . How we implement these CRUD operations in  asp.net web api.
create webapi application
In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.


I will take one sample  Employee table with valid data
create one Employee table in database
Create Table Employee
(
EmployeeID int PRIMARY KEY identity(1,1),
Name varchar(50),
Age int,
Salary int
)
insert into Employee values('sasishekaraya',25,40000)

like this insert 2 more records

create one model name it as Employee

model is an object that represents the data in your application. In ASP.NET Web API, you can use strongly typed CLR objects as models, and they will automatically be serialized to XML or JSON for the client.
           
public class Employee
    {
        public int EmployeeID { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
    }


The Database context class is Enity framework object.This class contains all collections of entities that map to tables in the database. The controller has to be access this Database context class so that it can perform CRUD operations.

Add database context class

public class DatabaseContext:DbContext
    {
        public DatabaseContext()
            : base("Name=DatabaseContext")
        {
            Database.SetInitializer<DatabaseContext>(null);
        }
        public DbSet<Employee> employee { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Employee>().ToTable("employee");
        }

    }



Install Entiry Framework From Manage NugetPackage

DbSet class is one of most important object in Entity framework.DbSet represents collection of entities.DbSet<TEntity> is generic version.


In web.config

<connectionStrings>
  
  <add name="DataBaseContext" connectionString="Data Source=SQLEXPRESS;Initial Catalog=Sample;Persist Security Info=True;User ID=sa;Password=007" providerName="System.Data.SqlClient" />
  </connectionStrings>

Add a web api controller,it handles the incoming  http requests

Create a controller name it as Employee

In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.

The Employee API will expose several "read" actions as HTTP GET methods. Each action will correspond to a method in the ProductsController class.

public class EmployeeController : ApiController
    {
        DatabaseContext db = new DatabaseContext();

//This method is used to get Employee Details based on EmployeedID
        public Employee GetEmp(int id)
        {
            var emp = db.employee.FirstOrDefault(p => p.EmployeeID == id);
            return emp;
        }


//This method is used to add Employee to Database
        [HttpPost]                             
        public string AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            return "Success";
        }
Or to post employee details to database
[HttpPost]
        public HttpResponseMessage AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

            string uri = Url.Link("DefaultApi", new { id = emp.EmployeeID });
            response.Headers.Location = new Uri(uri);
            return response;

        }

Notice that the method return type is now HttpResponseMessage. By returning an HttpResponseMessage instead of a Employee, we can control the details of the HTTP response message, including the status code and the Location header.




//This method is used to get list of employees
        public List<Employee> GetAllEmployees()
        {
            var lstemps = db.employee.ToList();
            return lstemps;
        }
    }


This method is used to Update Employee Details
 //To update Employee Details
        [HttpPut]
        public string UpdateEmployee(Employee emp)
        {
            Employee empdetails = db.employee.Find(emp.EmployeeID);
            empdetails.Age = emp.Age;
            empdetails.Name = emp.Name;
            empdetails.Salary = emp.Salary;           
            db.SaveChanges();
            return "Success";
        }

This method is used to remove Employee Details


// To remove employee Details
        public string DeleteEmployee(int id)
        {
            Employee empdetails = db.employee.Find(id);
            db.employee.Remove(empdetails);
            db.SaveChanges();
            return   "Success";
        }

db.SaveChanges() method is used to save the changes to the database.

Employee Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiCRUD.Models;

namespace WebApiCRUD.Controllers
{
    public class EmployeeController : ApiController
    {
        DatabaseContext db = new DatabaseContext();
        public Employee GetEmp(int id)
        {
            var emp = db.employee.FirstOrDefault(p => p.EmployeeID == id);
            return emp;
        }
        [HttpPost]
        public HttpResponseMessage AddEmployee(Employee emp)
        {
            db.employee.Add(emp);
            db.SaveChanges();
            var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, emp);

            string uri = Url.Link("DefaultApi", new { id = emp.EmployeeID });
            response.Headers.Location = new Uri(uri);
            return response;

        }
        public List<Employee> GetAllEmployees()
        {
            var lstemps = db.employee.ToList();
            return lstemps;
        }

        //To update Employee Details
        [HttpPut]
        public string UpdateEmployee(Employee emp)
        {
            Employee empdetails = db.employee.Find(emp.EmployeeID);
            empdetails.Age = emp.Age;
            empdetails.Name = emp.Name;
            empdetails.Salary = emp.Salary;           
            db.SaveChanges();
            return "Success";
        }
        // To remove employee Details
        public string DeleteEmployee(int id)
        {
            Employee empdetails = db.employee.Find(id);
            db.employee.Remove(empdetails);
            db.SaveChanges();
            return   "Success";
        }

    }
}




Test api

Rightclick on project =>manage nugget package=>search as testclient


we will get A ‘simple Test Client For Asp.Net Web Api’  click on install




Now run the Application




Click on the GetEmployee



click on TestApi





give the id and click on send you will get  the following result



tags:Web api curd operations,create ,update and delete in web api,curd operations web api 2.2 , curd operations in asp.net web api,sample web api application,realtime web api application and curd operations,web api headers and post data, web api employee curd operations,employee web api,employee asp.net web api.



Tuesday, 28 July 2015

ChildACtionOnly Attribute in Mvc

Any action method that is decorated with ChildActionOnly attribute is a child action method
Child action methods  will not respond to URL requests. If an attempt is made, a runtime error will be thrown stating –child action is accessible only by   a child request.
Child action methods can be invoked by making child request from a view using “Action()” and “RenderAction() ” html helpers.
An action method doesn’t need o have childactiononly attribute to be used as a child action, but use this attribute to be used as a child action, but use this attribute to prevent a action method from being invoked as a result of user request.
Child actions are typically associated with partial views, but this is not compulsory.
Child action methods are different from Non Action methods, in that non action methods cannot be invoked using Action() or RenderAction() helpers.

Here i will explain about ChildActionOnly Attribute
Create one sample controller in your mvc application,write two action methods name it as index and childaction methods and add respective views .

 public ActionResult Index()

        {

            ViewBag.TempValue = "Index action called at Sample controller";

            return View();

        }


        [ChildActionOnly]

        public ActionResult ChildAction(string param)

        {

            ViewBag.Message = "Child Action Called"+param;

            return View();

        }


suppose if we call Childaction method through url you will get an error.
Child action methods  will not respond to URL requests. If an attempt is made, a runtime error will be thrown stating –child action is accessible only by   a child request.







Now we need to call the childaction method from index view

@{

    ViewBag.Title = "Index";

}

<h2>Index</h2>

<h3>@ViewBag.TempValue  </h3>  

@Html.Action("ChildAction", "Sample", new {param=" first time" })



Here we are passing one parameter ,so that we will get this in index view.

let's see childaction view 


@{

    ViewBag.Title = "ChildAction";

}

<h2>ChildAction</h2>

<h3>@ViewBag.Message</h3>

now call the index action method in sample controller 

the child action view will see with in the index view

Using child action methods, it is possible to cache portions of a view. This is main advantage of child action methods

tags:child action attribute in mvc 5,child action attribute in mvc 6,child action attribute in mvc 4,action filters in mvc,
filters mvc5,filters in mvc 4,filters in mvc6,child action filter in mvc,child action method,action method in mvc 5,action methods in mvc 5,action methods in mvc 6