Thursday, July 27, 2017

ASP.Net MVC - Multiple Models in Single View - Part2

In last post, we have talked about different approaches to pass the multiple models in single view. We have also looked some of them like Dynamic,View Data and View Bag.

This post is the continuation of previous post. Here we will see the use of ViewModel,Tuple and ViewComponent for passing multiple model in single view . Let's first see what was our problem statement-

Problem Statement

We have two models Student and Course and we need to show the the list of Students and Courses in a single view.

Below are the model definition for Student and Course
public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }       
}

public class Course
{
    public int CourseID { get; set; }
    public string CourseName { get; set; }
}

Solutions to achieve

Here we will see ViewModel,Tuple and ViewComponent to achieve our requirement

1. View Model

ViewModel is a class which contains the properties which are represented in view or represents the data that we want to display on our view.

If we want to create a View where we want to display list of Students and Courses then we will create our View Model (StudentCourseViewModel.cs).

Tuesday, July 25, 2017

ASP.Net MVC - Multiple Models in Single View - Part1

In MVC we cannot use multiple model tag on a view. But Many times we need to pass multiple models from controller to view or we want to show data from multiple model on a view. So In this post we will see the different ways to bind or pass the multiple models to single view.

Problem Statement

Lets suppose we have two models Student and Course and we need to show the the list of Students and Courses in a single view.

Below are the model definition for Student and Course
public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }       
}

public class Course
{
    public int CourseID { get; set; }
    public string CourseName { get; set; }
}

Below is the Repository class which have two method for returning the list of Students and Courses
public class Repository
{
    public static List<student> GetStudents()
    {
          return new List<student>{ new Student() { StudentID = 1, StudentName = "Manish" },
                 new Student() { StudentID = 2, StudentName = "Prashant" },
                 new Student() { StudentID = 3, StudentName = "Deepak" }
                 };
     }
     public static List<course> GetCourses()
     {
          return new List<course> {
                 new Course () {  CourseID = 1, CourseName = "Chemistry"},
                 new Course () {  CourseID = 2, CourseName = "Physics"},
                 new Course () {  CourseID = 3, CourseName = "Math" },
                 new Course () {  CourseID = 4, CourseName = "Computer Science" }
                 };
     }
}

Thursday, July 13, 2017

Deserialize XML to C# object

In this post we will see the simple approach to deserialize XML to C# object.

Our XML String


string xmlString = "<Students><Student><Id>1</Id><Name>Manish Dubey</Name></Student><Student><Id>2</Id><Name>Pankaj</Name></Student></Students>";

Create our class


public class Student
{
  public int Id { get; set; }
  public string Name { get; set; }
}

Create XML Serializer and StringReader Object


//First argument is type of object and second argument is root attribute of your XML string/source

  XmlSerializer serializer = new XmlSerializer(typeof(List<student>), new XmlRootAttribute("Students"));
  StringReader stringReader = new StringReader(xmlString);

At last, deserialize XMl to C# object


List<student> studentList = (List<student>)serializer.Deserialize(stringReader);

Output

deseralize-xml-to-c#-object
Add caption


Friday, July 7, 2017

ASP.Net MVC - Custom Model Binding

custom-model-binding
In last article, we have discussed about what is ASP.NET Model binding and saw a basic introduction to the Model Binder. In this post we will see creating Custom Model Binding in ASP.Net MVC with simple example.

Model Binder in ASP.NET MVC

For model binding MVC uses the following types-

IModelBinder interface - This defines methods that are required for a Model Binder, like the BindModelAsync method. This method is responsible for binding a model to some values using ModelBindingContext

IModelBinderProvider interface - This interface contains methods that enables dynamic implementation of model binding for classes which implement the IModelBinder interface. This is used to manage the custom binder for the type of data posted by the end-user in views.

Creating Custom Model Binder

We creating our custom model binder by implementing the IModelBinder and IModelBinderProvider interfaces. Let see how we will do that.

Note :I have used ASP.Net MVC Core project here.All the codes are in ASP.Net MVC Core.

Tuesday, October 6, 2015

C# : What is New in C# 6.0?


New features in C#6.0
In this post we will see the newly added features in C# 6.0. In C# 6.0 some very cool features has been added like "Auto-property Enhancements", "Primary Constructors", "Expressions as Function Body", "Use of Static", "Exception Filters", "inline declarations", "nameof Expressions", "Null-conditional Operators", "String interpolation", "Await in catch and finally".





Introduction

Here, you will find nine new cool features of C# 6.0:

  1. Auto-property Enhancements
  2. Parameters on Classes and Structs
  3. Using Static
  4. Exception Filters
  5. Null-conditional Operators
  6. Index Initializers
  7. $ sign
  8. String Interpolation
  9. nameof Expression
  10. Await in catch and finally block

Saturday, November 15, 2014

Conversion of Decimal to Binary in C#

In interviews, there are some programming questions which you will find most of the places like Write a program to reverse the string or Write a program to check string are palindrome or not etc..

In this post, I have a picked a question from that type of programming questions i.e.

Write a program for converting the decimal value to binary value?

Below is the simple method for converting a decimal value into binary value  :

Code Snippet


/// <summary>
/// Method for converting Decimal to Binary
/// </summary>
/// <param name="_value">integer value</param>
/// <returns></returns>
static string DecimalToBinary(int _value)
{
  string strBinary = string.Empty;
  while (_value >= 1)
   {
     strBinary = (_value % 2).ToString() + strBinary;
     _value = _value / 2;
   }
   return strBinary;
}

Thursday, August 29, 2013

C#: Difference between “throw” and “throw ex” in C# .Net Exception

In day to day development, we all are very familiar with Exception  handling. We pretty much all know that we should wrap the code which may cause for any error in try/catch block and do something about error like give a error message to end user. Here I am not going to explain about Exception handling in C#. Instead I am going to talk about a particular aspect of Exception  handling, which is "throw" vs "throw ex".

You can also find my other articles related to C#ASP.Net jQuery, Java Script and SQL Server. I am writing this post because I was asked this question recently in a interview and unfortunately I didn't  know the answer. So I am posting this for those guys who uses "throw" and "throw ex" frequently but don't know the differences (not all,some knows).

Difference between “throw” and “throw ex”

Take a look on the below code snippest-
throw ex throw

try
{
   //Code which fails and raise the error
}
catch (Exception ex)
{
   throw ex;
}

try
{
   //Code which fails and raise the error
}
catch (Exception ex)
{
   throw;
}

Wednesday, August 14, 2013

LINQ- Difference between First and FirstOrDefault- First vs FirstOrDefault

In my previous post Single vs SingleOrDefault, we talk about Single and SingleOrDefault method and difference between these methods. In this post we are going to explore two more extension methods First and FirstOrDefault.


You can find some other useful topics and posts here. Below is a chart explaining about First() and FirstOrDefault(). You can easily differentiate these methods from this chart. I have also given examples of each method.

Tuesday, July 23, 2013

How To- Send DataGridView Data in Email in Window Form Application

In my one post I explained you how to Send Grdiview Data in Email. Here I am going to show you how to send DataGridview content in E-mail in window application.

You can also find my other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

First take a look on the below image.
DataGridView with Data

Saturday, June 22, 2013

How To- Bind Data to Gridview using jQuery in ASP.Net

In this post, I am explaining how to bind data to Gridview using jQuery in ASP.Net through Ajax call.

In previous posts, I explained Page Scroll to Top with jQuery, Automatically Refresh Page Using Java Script , How to Create a Textarea Character Counter, Animated Sliding Recent Post Widget For Blogger, Change Input to Upper Case using Java Script, Calculate Age from Date of Birth Using Java Script, jQuery .toggleClass() example and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

ASPX Page

Gridview Markup
<asp:GridView ID="grdDemo" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
    Font-Size="10pt" HeaderStyle-BackColor="GrayText" HeaderStyle-ForeColor="White" Width="500px">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" />
        <asp:BoundField DataField="FName" HeaderText="First Name"/>
        <asp:BoundField DataField="LName" HeaderText="Last Name"/>
        <asp:BoundField DataField="Email" HeaderText="E-mail"/>
    </Columns>
</asp:GridView>

Monday, May 27, 2013

How To- Export Gridview to PDF in ASP.Net with Image

In one of my previous articles I explained Export Gridview to PDF in ASP.Net . Here, I am explaining how to export Gridview to PDF which has images and pictures in it.

In my previous posts, I explained Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

Exporting Gridview to PDF


For exporting the data, I am using the iTextSharp (third party dll) in this post. Download the iTextSharp .
I have following Table which contains the Image Information like Image Name and Image Path.
Export Gridview to PDF in ASP.Net with Image
For exporting images into PDF we need to convert the ImagePath shown in table into its absolute URl. For example, In the above image-

Tuesday, May 21, 2013

C#- Find Similarity between Two Strings in Percentage

In this post, I am explaining how can you check the similarity between two strings in terms of percentage in  C# ? To check similarity between two strings we have formula by which we can find similarity in %.

In my previous posts, I explained Create Hindi TextBox Using Google Transliteration in ASP.Net, Convert Multipage Tiff file into PDF in ASP.Net using C#, Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

The formula to check the similarity between two strings in % is-

Thursday, May 16, 2013

ASP.Net- Create Hindi TextBox Using Google Transliteration in ASP.Net

Hindi Textbox in ASp.Net
Here, I am explaining you how to create a hindi textbox in  ASP.Net using  Google Transliteration.Here I am mainly targeting english to hindi transliteration. You can use any language which is supported by Google.

In my previous posts, I explained Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

To create a Hindi textbox in  ASP.Net using Google Transliteration, you have to add the following script source into your ASPX page.

Tuesday, May 14, 2013

How To- Convert Multipage Tiff file into PDF in ASP.Net using C#

Multipage Tiff to PDF
Here, I am explaining how to convert a multipage tiff file into PDF file in C#. Sometimes we have a requirement to convert the multipage tiff file into PDF.I am using the iTextSharp (third party dll) for conversion of multipage tiff file into PDF file.

In my previous posts, I explained Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

Before starting the sample code, First of all download the iTextSharp and add the reference of following dll into your application.
itextsharp.dll

Tuesday, May 7, 2013

How To- Send mail in ASP.Net using C#, VB.Net

Send Mail in C#
This post is basically for freshers or newbies. In application development sometimes we need to send the mail through our application. Here I am explaining how you can send mail in ASP.Net using C#, VB.Net.

In my previous posts, I explained Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

The Microsoft .NET framework provides two namespaces, System.Net and System.Net.Sockets for managed implementation of Internet protocols that applications can use to send or receive data over the Internet.We use the SMTP protocol for sending mail in  C# .

Friday, May 3, 2013

How To- Create Zip FIle in ASP.Net Using C#, VB.Net

Zip File in Asp.Net
Here, I am explaining how to Create a zip file in ASp.Net Using C# and VB.Net. We can easily Create Zip Files Archives using DotNetZip Library.

In my previous posts, I explained Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

For creating zip file add the reference of  Ionic.Zip.dll in your application and add following namespace-
using Ionic.Zip;
Place one FileUpload control on aspx page and one button to upload files and create zip file in it's Click Event.
Create Zip File in ASP.Net

Tuesday, April 30, 2013

How To- Convert Data Table into List

DataTable To List
Recently I have posted an article Convert a Generic List to a Datatable. Today I am explaining here the reverse way of my previous article i.e conversion of DataTable into List.

You may also like these posts Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C#Partial Methods, Contextual KeywordC# Static Methods and some other articles related to C#ASP.Net and SQL Server.

 So Lets start the conversion of DataTable into List. First of all add the following namespaces-
^ Scroll to Top