Wednesday, October 29, 2014

Show data from a database table content in MVC 4.0 razor

In this MVC tutorial post I will show you how to show a database content to a page in MVC 4.0. So for those who are not aware of MVC (Model View Controller) concept you can visit this post  as a reference.

So first create a new MVC project. Select Razor as your View engine.
Create a new database named what ever you want and add a new table named tblEmployee.Design your database as following.


And after that add an EmployeeController in the Controller folder.

And after that add an Empployee.cs in the Model folder. Add the following code into the Employee.cs.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace MvcApplication1.Models
{
    [Table("tblEmployee")]
    public class Employee
    {
        [Key]
        public int empid { get; set; }
        public string name { get; set; }
        public string dept { get; set; }
    }

}

I set the Table attribute to tblEmployee as to connect the tblEmployee table with Employee class. Normally it takes the class name as the class name. But here our class name is differ from class name. So I did it.
Now add another class named EmployeeContext.cs into the Model folder again. Its is to connect the connection string in Web.Config file.
Write down the following code in the EmployeeContext.cs
using System.Data.Entity;

public class EmployeeContext : DbContext
{
    public DbSet employee { get; set; }
}

Add the connection string in the web.config as a name EmployeeContext. Now come back to EmpployeeController. Add a View of Indes Action. Doing this choose create a strongly typed view and select Employee. If Employee is not showing then do not get panic. Just build the solution once. It will show the Employee in to the drop down list to choose. Now in the Index.cshtml in View add the following code.
@using MvcApplication1.Models;
@using System.Web.Mvc;

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

All Employee Details

@foreach(Employee emp in @Model) { }
@emp.dept @emp.name @emp.dept

In the EmployeeController write down the code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            EmployeeContext emp = new EmployeeContext();
            List employee1 = emp.employee.ToList();

            return View(employee1); // return list of employee
        }
    }
}

Now run your project and enter the URL localhost://Employee/Index

Download the full source code here.

Sunday, October 19, 2014

How to bind a HTML Drop Down List with Web Services in ASP.NET using C#

Introduction :
In this article I will show you how to bind a Drop Down List in ASP.NET site with a web services. Before starting we need to know what is a Web Services is. Then we will know how to bind the Drop Down List with the help of that Web Service.

Web Services :
According to Tutorials point Web Services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or Web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.

In web services we use WebMethod to call with parameter and to do operations. A web Services is inherited by class System.Web.Services.WebService. To check my Web Service article click here.

Starting With a Web Service : 
To start process with a Web Service create a new project, add a new Web Form. To add a new Web Service go to Add New Item. And then add a new Web Service (.asmx). Name it as you want.
 Now in the Web Form add a new HTML  Drop Down List. We will use the Web Service to bind the HTML Drop Down List.



Now we will check the following JQuery json code.
$(document).ready(function () {
            load_ddlFrom();
        });

function load_ddlFrom() {
  $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "services/Bind.asmx/LoadddlForm",
                data: "{}",
                dataType: "json",
                success: function (Result) {
                    Result = Result.d;
                    $.each(Result, function (key, value) {
                        $("#ddlFrom").append($("").val
                        (value.Id).html(value.Stopage));
                    });
                },
                error: function (Result) {
                    alert("Error");
                }
            });
        }

Lets check the url carefully  services/Bind.asmx/LoadddlForm 
services is the folder name where all the services are stored, I didn't use any thing before it because it is locketed in the root folder. Then Bind.asmx is the name of the web services that you are accessing. And the last one  LoadForm. It is the method name that you are invoking.  So lets check what is written in the LoadForm method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace Demo.services
{
    /// 
    /// Summary description for Bind
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class Bind : System.Web.Services.WebService
    {
        public class CountryInfo
        {
            public int Id { get; set; }
            public string Stopage { get; set; }
        }
        public List CountryInformation { get; set; }

        [WebMethod]
        public List LoadddlForm()
        {
            CountryInfo ci = new CountryInfo();
            List CountryInformation = new List();
            DataSet ds;
            using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["booking"].ToString()))
            {
                using (SqlCommand cmd = new SqlCommand("select Id,Stopage from tblStopageMeta where isdelete=0", con))
                {
                    con.Open();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {

                        ds = new DataSet();
                        da.Fill(ds);
                    }
                }
            }
            try
            {
                if (ds != null)
                {
                    if (ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                CountryInformation.Add(new CountryInfo()
                                {
                                    Id = Convert.ToInt32(dr["Id"]),
                                    Stopage = dr["Stopage"].ToString()
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return CountryInformation;
        }
    }
}

Now run your project and check whether it is binding your HTML Drop Down List or not. But before that one create your database and database connection in Web.Config.
 

Saturday, October 4, 2014

XML and .NET

XML - Extensible Markup Language is a markup language like HTML designed for describing data as a database.

Topics to discuss :
  • Definition
  • How to write tags XML
  • Create a XML file in .NET
  • Data read from XML using ASP.NET C#
  • Edit or Update data in XML using ASP.NET C#
  • Search in XML document (Where clause)
Definition of XML :

According to Wikipedia definition of XML is.
Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. 
How to write tags in XML :

As I told previously it is like HTML, a markup language, so its clear it will be written with the help of markup tags as we write HTML. Lets check a sample of XML.


   
     1
     C
     Dennis Ritchie
   
   
     2
     C#
     Anders Hejlsberg
   
   
     3
     Ruby
     Yukihiro "Matz" Matsumoto
   
 

Its looks like a database...Where data are defined in a tree structure with child and sub child. The whole XML structure are like.

   
     ...Data...
   
 

   
     ...Data...
   
 

   
     ...Data...
   
 

Hope its clear how XML is organized to store data and perform. Now lets check next topic, write into XML using C#.

Create a XML file in .NET:

To write  a XML file in ASP.NET using C# you need to add a new namespace.

using System.Xml;

And one extra class named XmlWriter. Create an object of XmlWriter and using that object we will create a XML file and also write into it. How? Lets check the following code thoroughly.
Language[] lang= new Language[3];
employees[0] = new Employee(1, "C", "Dennis Ritchie");
employees[1] = new Employee(2, "C#", "Anders Hejlsberg");
employees[2] = new Employee(3, "Ruby", "Yukihiro "Matz" Matsumoto");

using (XmlWriter writer = XmlWriter.Create("ComLang.xml"))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Computer");

    foreach Language lang1 in lang)
    {
        writer.WriteStartElement("Language");

 writer.WriteElementString("ID", employee.Id.ToString());
 writer.WriteElementString("title", employee.FirstName);
 writer.WriteElementString("author", employee.LastName);

 writer.WriteEndElement();
    }
 
    writer.WriteEndElement();
    writer.WriteEndDocument();
}

Read from a XML file :

After creating a XML file now its time to show the data. To view data the best one is GridView. So we will use GridView here to show the data of a XML file. You can bind a GridView with a XML file by 2 methods. First one is little bit simpler using XMLDataSource. And second one is the greatest way to do....CODING... :). No doubt I will show by second method.

So, take a GridView and on the PageLoad method write down the following code.


    
        
        
        
    


Now the C# code
using System.Data;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        fillGrid();
    }
}
 
private void fillGrid()
{
    using (DataSet ds = new DataSet())
    {
        ds.ReadXml(Server.MapPath("~/ComLang.xml"));
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

Creating and bindng is over. Its time to edit and update.

Edit or Update data in XML :

We will edit a node of the XML file used. Lets assume we will change the author of language C. So how will code? Lets check.

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("~/ComLang.xml"));

XmlNodeList nodeList = xmlDoc.SelectNodes("/computer/language");
// Chnange the author name of C to TextBox value
nodeList[0].ChildNodes[1].InnerText = txtAuhor.Text;
xmlDoc.Save(Server.MapPath("~/ComLang.xml"));
Response.Write("Succcessfully updated !");

nodeList[0].ChildNodes[1] means the second attribute of 1st node. A simple 2D matrix. So change it according to you attribute.
Search in XML document Now in your mind one question may arise, here Arka has shown only by a particular attribute, what about the others, if I don't know at which position C language node is present. Remember we have taken a ID attribute with out node. We will use that one to edit or update. Lets check how to to do this. This is like Where clause in XML.

XDocument document = XDocument.Load(Server.MapPath("~/ComLang.xml"));

var q = from r in document.Descendants("Language") where (int)r.Element("ID") ="+ txtID.Text +" select new {
 Title = r.Element("title").Value, Author = r.Element("author").Value };

GridView1.DataSource = q;
GridView1.DataBind();

Now I hope its clear how to fetch a particular row of a XML document.
I thing this post will clear the whole confusions about XML and how to use XML. If you still have some confusion don't hesitate to ask me any thing. That is all for this time....Practice yourself...Happy coding :)

Friday, October 3, 2014

Print a DIV or Panel in ASP.NET C# JavaScript

Hello, today I will show you how to print a div or panel in your ASP.NET page using JavaScript and Jquery with the help of a button. Normally to print we use windows.print() option to print the whole page. but if we need to print a particular portion of a page then what to do? Solution is here.

Create a new page and add a div or ASP panel and after finishing the div add an Button. We don't need to generate the click event of the button, because we are just use it as a normal button and call JavaScript function using this. in the div write your all data, which you want to print.

Check the bellow code.


Your all data goes here....



aNow its time for dome JavaScript code to handle...

function printDiv() {
 //Get the HTML of div
 var divElements = document.getElementById("<%= PanelDiv.ClientID %>").innerHTML;
 //Get the HTML of whole page
 var oldPage = document.body.innerHTML;

 //Reset the page's HTML with div's HTML only
 document.body.innerHTML =
   "" +
   divElements + "";

 //Print Page
 window.print();

 //Restore orignal HTML
 document.body.innerHTML = oldPage;
}

Now run your project. We have use PanelDiv.ClientID because its an ASP control and its the process to access the server side controls into client side code. Hope it helps you... Happy coding ... :)

Follow by Email

Popular Posts

Pageviews