Tuesday, February 26, 2013

Loading dropdownlist in MVC2 and MVC4

Loading doropdownlist in MVC2 and MVC4.


This is the code you will write in Models, here you create a cs file called ProfileModel inside Models folder an write the following code.

public interface IAdminService
    {
        List< tblCountry > GetCountries();
    }


    public class AdminService : IAdminService
    {
        /* this you can cosider as data provider, like any Services, any other assembly etc. */
AdminDTO _adminProvider;
        MasterDTO _masterProvider;

        public AdminService()
        {
            _adminProvider = new AdminDTO();
            _masterProvider = new MasterDTO();
        }


        public List< tblCountry > GetCountries()
        {
            return MasterDTO.GetContries();
        }
    }

now here we see how to call the dataService in controller

public class ProfileController : Controller
    {

        public IDataService dataService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if dataService == null) { dataService = new DataService(); }

            base.Initialize(requestContext);
        }


/* this is an example of view implementation in example  */
[HttpGet]
        public ActionResult ManageProfile()
        {
            ViewBag.Countries = dataService.GetCountries();
            ViewBag.Message = string.Format("There are {0} contries", dataService.GetCountries().Count);


            List countryList = (from p in
                                                   dataService.GetCountries().ToList()
                                               select new SelectListItem()
                                               {
                                                   Value = p.CountryId.ToString(),
                                                   Text = p.CountryName
                                               }).ToList();

            ViewBag.CountryDropdown = countryList;

            return View();
        }
}

Now your view is ready with data, you just need to display on screen , so here is how you can achieve that.
In "Views" folder you need to create a folder called "Profile", inside the "Profile" folder create a razor page with name ManageProfile, and write the code below.


this is an example of country dorpdown, "CountryDropdown" is nothing but the variable of your view bag
@Html.DropDownList("CountryDropdown")


  this is an example of how the collection object can be displayed like datalist/gridview/collectionbinding
    @{
        var countries = ViewBag.Countries;
    }
    < table >
        @foreach (tblCountry c in countries)
        {
            < tr >
                < td >@c.CountryId
                < /td >
                < td >
                    @Html.ActionLink(c.CountryName, "AddEditState", new { cid = c.CountryId, name = c.CountryName });
                < /td >
                < td >@c.CurrencyCode
                < /td >
                < td >@c.Currency
                < /td >
                < td >@c.Capital
                < /td >
                < td >@c.Population
                < /td >
            < /tr >
        }
    < /table >


 please note : example how to pass parameters with Html.ActionLink()  @Html.ActionLink(c.CountryName, "AddEditState", new { cid = c.CountryId, name = c.CountryName });




Tuesday, February 19, 2013

WCF Rest example

Create a WCF Service, Delete the default added service and follow the steps below.

Step 1: Create a object called Student, this object we use in our example


 [DataContract]
    public class Student
    {
        [DataMember]
        public int StudentId { get; set; }

        [DataMember]
        public int ClassId { get; set; }

        [DataMember]
        public string Firstname { get; set; }

        [DataMember]
        public string Lastname { get; set; }
    }

Now create a WCF service with any business name as per your requirement, here i have created a service called RestfulServiceExample.svc , open the interface created with name IRestfulServiceExample, here i have added four example of Json and XML with single object and collection object

Here is how the definition would look like.

using System.ServiceModel;
using System.ServiceModel.Web;
using WcfRestExample.BusinessObjects;
using System.Collections.Generic;

namespace WcfRestExample
{

    [ServiceContract(Namespace = "http://arindamachakraborty.blogspot.in")]
    public interface IRestfulServiceExample
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "xml/{id}")]
        Student XMLStudent(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "json/{id}")]
        Student JSONStudent(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Xml,
            RequestFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "xmls/{id}")]
        List XMLStudents(string id);


        [OperationContract]
        [WebInvoke(Method = "GET",
           ResponseFormat = WebMessageFormat.Json,
           RequestFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Wrapped,
           UriTemplate = "jsons/{id}")]
        List JSONStudents(string id);
    }
}

Note : in WebInvoke attribute Method value is case sensitive, that should always be  Method = "GET", not Method = "Get" or Method = "get"

Now lets look at the implementation of interface.


public class RestfulServiceExample : IRestfulServiceExample
    {

        public Student JSONStudent(string id)
        {
            return new Student()
            {
                ClassId = 1,
                StudentId = 2,
                Firstname = "Arindam",
                Lastname = "Chakraborty"
            };
        }

        public Student XMLStudent(string id)
        {
            return new Student()
            {
                ClassId = 1,
                StudentId = 2,
                Firstname = "Arindam",
                Lastname = "Chakraborty"
            };
        }


        public List< Student > XMLStudents(string id)
        {
            List< Student > students = new List< Student >();
            students.Add(new Student(){ ClassId=1, Firstname="Arindam", Lastname="Chakraborty", StudentId=1 });
            students.Add(new Student() { ClassId = 2, Firstname = "Richa", Lastname = "Pandit", StudentId = 2 });
            students.Add(new Student() { ClassId = 3, Firstname = "Soham", Lastname = "Khanna", StudentId = 3 });


            return students;
        }

        public List< Student > JSONStudents(string id)
        {
            List< Student  > students = new List< Student >();
            students.Add(new Student() { ClassId = 1, Firstname = "Arindam", Lastname = "Chakraborty", StudentId = 1 });
            students.Add(new Student() { ClassId = 2, Firstname = "Richa", Lastname = "Pandit", StudentId = 2 });
            students.Add(new Student() { ClassId = 3, Firstname = "Soham", Lastname = "Khanna", StudentId = 3 });
         
            return students;
        }
    }

We are done with service development, now we look at service configuration and how to publish

< system.serviceModel >
    < services >
      < service name="WcfRestExample.RestfulServiceExample" behaviorConfiguration="ServiceBehavior" >
        < endpoint  binding="webHttpBinding"
                  contract="WcfRestExample.IRestfulServiceExample"
                  behaviorConfiguration="web" >
        < /endpoint >
      < /service >
    < /services >

Notice we have set binding="webHttpBinding"

    < behaviors >
      < serviceBehaviors >
        < behavior name="ServiceBehavior" >
          < !-- To avoid disclosing metadata information,
          set the value below to false
          and remove the metadata endpoint above before deployment -- >
          < serviceMetadata httpGetEnabled="true"/ >
          < !-- To receive exception details in faults for
          debugging purposes, set the value below to true.
          Set to false before deployment to avoid disclosing
          exception information -- >
          < serviceDebug includeExceptionDetailInFaults="false"/ >
        < /behavior >
      < /serviceBehaviors >
      < endpointBehaviors >
        < behavior name="web" >
          < webHttp / >
        < /behavior >
      < /endpointBehaviors >
    < /behaviors >
    < serviceHostingEnvironment multipleSiteBindingsEnabled="true" / >
  < /system.serviceModel >

Now we have successfully built and published the service, so its time to test the service, so you can see how the end result will look like.

Here is the url you need to run
http://machinename/servicename/xml - xml output for single objetc
http://machinename/servicename/xmls - xml output for collection object
http://machinename/servicename/json - json single object
http://machinename/servicename/jsons -  json output collection objects

ETG Consultancy

Web Designing Development Analysis & Promotion
Asp.Net 2.0 SQL WWF WCF SEO Marketing Ajax JQuery NHibernate MVC