Friday, March 30, 2012

Demo for Linq to Sql dbml with Mvp(Model View Presenter pattern ).


Here is Simple Demo for Linq to Sql  dml with Mvp(Model View Presenter pattern ).This will explain you about Insert update and delete and selection of linq to sql using MVP implication.Here I have create very simple database which will contain 2 table which have one to one relation ship Here I have display diagram view of my simple database.
image
now as per display below image database contain 2 table
1. Pet
2. Owner
let me explain related to MVP pattern what I understand about it.   mvp is nothing but just project Architecture for big length and complex project. so using this type of method you can easily manage and provided more security and easily test your code. create separate project for each layer.
let me explain how I have implicated mvp in my project
Here is list of project required to create.
1.Module (contain dbml file for database)
2.Entity Access (required to create class of all entity in our case Pet and Owner class )
3.Task Project (contain inter face for process and task class for pet and owner entity)
4. Pesenter  (contain presenter interface and presenter class which will pass data from view to task or vice versa
5.Main project of view
Here is screen shot for solution
image
 
now let me explain all process step by step project from bottom to top
Create One Class Library Project add app.config file in project
create one dbml file like Pet.dbml and drag and drop both table from server explorer give relationship between 2 tables
like I have display in first diagramed.  if you notice that app.config file contain connection related information.
Create one class which name given same as dbml  file. now make this class as partial class of context class and overwrite connection string Here is my code for overwrite class
   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using System.Configuration;
   6:   
   7:  namespace TestModule
   8:  {
   9:      public partial class PetDataContext
  10:      {
  11:          public PetDataContext()
  12:              : base(ConfigurationManager.ConnectionStrings["TestModule.Properties.Settings.PetsConnectionString"].ConnectionString, mappingSource)
  13:          {
  14:              OnCreated();
  15:          }
  16:   
  17:          partial void OnCreated()
  18:          {
  19:              this.CommandTimeout = 3600;
  20:          }
  21:   
  22:      }
  23:  }





now from dbml designer required to remove same constructer which we have created in partial class.

   1:   
   2:      [global::System.Data.Linq.Mapping.DatabaseAttribute(Name="Pets")]
   3:      public partial class PetDataContext : System.Data.Linq.DataContext
   4:      {
   5:          
   6:          private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
   7:          
   8:      #region Extensibility Method Definitions
   9:      partial void OnCreated();
  10:      partial void InsertPet(Pet instance);
  11:      partial void UpdatePet(Pet instance);
  12:      partial void DeletePet(Pet instance);
  13:      partial void InsertOwner(Owner instance);
  14:      partial void UpdateOwner(Owner instance);
  15:      partial void DeleteOwner(Owner instance);
  16:      #endregion
  17:          
  18:          //public PetDataContext() : 
  19:          //        base(global::TestModule.Properties.Settings.Default.PetsConnectionString, mappingSource)
  20:          //{
  21:          //    OnCreated();
  22:          //}
  23:          
  24:          public PetDataContext(string connection) : 
  25:                  base(connection, mappingSource)
  26:          {
  27:              OnCreated();
  28:          }



 
Now Required to create Entity Project as Class Library which contain simple property of all table

Here is both class

Owner.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:   
   6:  namespace Test.EntityAccess
   7:  {
   8:     public class Owner
   9:      {
  10:          public int Id { get; set; }
  11:          public string Name { get; set; }
  12:          public int Age { get; set; }
  13:      }
  14:  }





Pet.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:   
   6:  namespace Test.EntityAccess
   7:  {
   8:      public class Pet
   9:      {
  10:          public int id { get; set; }
  11:          public string PetName { get; set; }
  12:          public string Species { get; set; }
  13:          public DateTime BirthDay { get; set; }
  14:          public int OwnerId { get; set; }
  15:      }
  16:  }

Now Required to create Task Project as Class Library where we need to given reference to both project Model and Entity

Now Need to add Interface first where inter face contain Method which will required to override in class

here is 2 interface so more idea you will get

ItaskOwner.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Test.EntityAccess;
   6:   
   7:  namespace Test.Task.InterFace
   8:  {
   9:     public interface ITaskOwner
  10:      {
  11:         Owner GetOwner(Owner Owner);
  12:         IList<Owner> GetListOfOwner();
  13:   
  14:         bool AddOwner(Owner owner);
  15:      }
  16:  }



Itaskpet.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Test.EntityAccess;
   6:   
   7:  namespace Test.Task.InterFace
   8:  {
   9:      public interface ITaskPet
  10:      {
  11:          List<Pet> GetListOfPets();
  12:          Pet GetCurrentPet(Pet P);
  13:          bool AddPet(Pet P);
  14:   
  15:      }
  16:  }


Now Required to create Task Class Where we need to Implementation of all method
TaskOwner.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Test.Task.InterFace;
   6:  using TestModule;
   7:   
   8:  namespace Test.Task
   9:  {
  10:      public class TaskOwner : ITaskOwner
  11:      {               
  12:   
  13:          public EntityAccess.Owner GetOwner(EntityAccess.Owner Owner)
  14:          {
  15:              throw new NotImplementedException();
  16:          }
  17:   
  18:          public IList<EntityAccess.Owner> GetListOfOwner()
  19:          {
  20:              List<EntityAccess.Owner> ListofOwner;
  21:              using (PetDataContext db = new PetDataContext())
  22:              {
  23:                  ListofOwner = (from obj in db.Owners
  24:                                 select new EntityAccess.Owner()
  25:                              {
  26:                                 Age=Convert.ToInt32(obj.Age.Value),
  27:                                 Id=Convert.ToInt32(obj.Id),
  28:                                 Name=obj.Name                                           
  29:                              }).ToList();
  30:   
  31:                  
  32:              }
  33:              return ListofOwner;           
  34:          }
  35:   
  36:          public bool AddOwner(EntityAccess.Owner _owner)
  37:          {
  38:              try
  39:              {
  40:                  using (PetDataContext db = new PetDataContext())
  41:                  {
  42:                      Owner owner = new Owner();
  43:                      owner.Age = _owner.Age;
  44:                      owner.Name = _owner.Name;
  45:                      db.Owners.InsertOnSubmit(owner);
  46:                      db.SubmitChanges();
  47:                  }
  48:                  return true;
  49:   
  50:              }
  51:              catch (Exception)
  52:              {
  53:                  return false;
  54:              }            
  55:          }        
  56:      }
  57:  }



TaskPet.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Test.Task.InterFace;
   6:  using Test.EntityAccess;
   7:  using TestModule;
   8:   
   9:  namespace Test.Task
  10:  {
  11:      public class TaskPet : ITaskPet
  12:      {
  13:   
  14:          #region ITaskPet Members
  15:   
  16:          public List<EntityAccess.Pet> GetListOfPets()
  17:          {
  18:              List<EntityAccess.Pet> ListOfPets;
  19:              using (PetDataContext db = new PetDataContext())
  20:              {
  21:                  ListOfPets = (from c in db.Pets
  22:                                select new EntityAccess.Pet {
  23:                                    BirthDay = c.Birthday.HasValue ? c.Birthday.Value:new DateTime() ,
  24:                                    id=c.id,
  25:                                    OwnerId=Convert.ToInt32(c.OwnerId),
  26:                                    PetName=c.PetName,
  27:                                    Species=c.Species
  28:                                }).ToList();
  29:              }
  30:              return ListOfPets;
  31:          }
  32:   
  33:          public EntityAccess.Pet GetCurrentPet(EntityAccess.Pet P)
  34:          {
  35:              EntityAccess.Pet Pet = new EntityAccess.Pet();
  36:              using (PetDataContext db = new PetDataContext())
  37:              {
  38:                  Pet = (from obj in db.Pets
  39:                         where obj.PetName == P.PetName
  40:                         select new EntityAccess.Pet
  41:                         {
  42:                             id=obj.id,
  43:                             BirthDay=obj.Birthday.HasValue ? obj.Birthday.Value:new DateTime(),
  44:                             OwnerId=Convert.ToInt32(obj.OwnerId),
  45:                             PetName=obj.PetName,
  46:                             Species=obj.Species
  47:                         }).FirstOrDefault();
  48:              }
  49:              return Pet;
  50:          }
  51:   
  52:          bool ITaskPet.AddPet(EntityAccess.Pet P)
  53:          {
  54:              try
  55:              {
  56:                  using (PetDataContext db = new PetDataContext())
  57:                  {
  58:                      TestModule.Pet pet = new TestModule.Pet();
  59:                      pet.Birthday = P.BirthDay;
  60:                      pet.OwnerId = P.OwnerId;
  61:                      pet.PetName = P.PetName;
  62:                      pet.Species = P.Species;
  63:                      db.Pets.InsertOnSubmit(pet);
  64:                      db.SubmitChanges();
  65:                  }
  66:                  return true;
  67:              }
  68:              catch (Exception)
  69:              {
  70:                  return false;                
  71:              }            
  72:          }
  73:   
  74:          #endregion
  75:      }
  76:  }





Now we have ready structure for communication between .net and database

now required to create pool which will pass user input to task project and get result from task project and send to aspx page.

Create Presenter project same Class Library but here just method signature is available and pass interface from one level to other level

Presenter Project Contain ViewInterFace Folder where property will define

See below result so more idea you will get

IViewOwner.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Test.EntityAccess;
   6:   
   7:  namespace Presenter.Test.ViewInterFace
   8:  {
   9:      public interface IViewOwner
  10:      {
  11:          IList<Owner> ListOfOwner{get;set;}
  12:          Owner CurrentOwner { get; set; }
  13:          //Owner GetCurrentOwner(Owner Owner);
  14:      }
  15:  }

IViewPet.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Test.EntityAccess;
   6:   
   7:  namespace Presenter.Test.ViewInterFace
   8:  {
   9:      public interface  IViewPet
  10:      {
  11:          Pet Pet { get; set; }
  12:          IList<Pet> ListOfPet { get; set; }
  13:      }
  14:  }

now required create class which will communicated with aspx page and task project look and see how implication is done 

PresenterOwner.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Test.Task;
   6:  using Test.Task.InterFace;
   7:  using Test.EntityAccess;
   8:  using Presenter.Test.ViewInterFace;
   9:   
  10:  namespace Presenter.Test
  11:  {
  12:      public class PresenterOwner
  13:      {
  14:          private readonly IViewOwner _viewOwner;
  15:          private readonly ITaskOwner _taskOwner;
  16:   
  17:          public PresenterOwner(IViewOwner viewOwner):this(viewOwner,new TaskOwner()){}
  18:   
  19:          public PresenterOwner(IViewOwner viewOwner, ITaskOwner taskOwner)
  20:          {
  21:              _viewOwner = viewOwner;
  22:              _taskOwner = taskOwner;
  23:          }   
  24:       
  25:          public void GetLisofOwner()
  26:          {
  27:              _viewOwner.ListOfOwner = _taskOwner.GetListOfOwner();
  28:          }
  29:          public bool AddOwner(Owner Owner)
  30:          {
  31:              return _taskOwner.AddOwner(Owner);
  32:          }
  33:      }
  34:  }







PresenterPet.cs

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Text;
   5:  using Test.Task;
   6:  using Test.Task.InterFace;
   7:  using Presenter.Test.ViewInterFace;
   8:  using Test.EntityAccess;
   9:  namespace Presenter.Test
  10:  {
  11:     public class PresenterPet
  12:      {
  13:         private readonly ITaskPet _taskpet;
  14:         private readonly IViewPet _viewpet;
  15:   
  16:         public PresenterPet(IViewPet viewpet) : this(viewpet, new TaskPet()) { }
  17:   
  18:         public PresenterPet(IViewPet viewpet,ITaskPet taskpet)
  19:         {
  20:             _taskpet=taskpet;
  21:             _viewpet = viewpet;
  22:         }
  23:   
  24:         public void AddPet(Pet P)
  25:         {
  26:             _taskpet.AddPet(P);
  27:         }
  28:   
  29:      }
  30:  }
 















Now if you notice that presenter class constructer we need to pass interface with one parameter and it will also call other constructer with 2 parameter.

Now look at fine your aspx.page project

create new website here I have create siple page and make call for select , insert,update call using mvp pattern

LinqTest.aspx

   1:  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="LinqTest.aspx.cs" Inherits="DateControl.LinqTest" %>
   2:   
   3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:  <html xmlns="http://www.w3.org/1999/xhtml">
   5:  <head runat="server">
   6:      <title></title>
   7:  </head>
   8:  <body>
   9:      <form id="form1" runat="server">
  10:      <div>
  11:          <asp:TextBox ID="txtOwner" runat="server"></asp:TextBox>
  12:          <asp:Button ID="btnaddowner" runat="server" Text="AddOwner" OnClick="btnaddowner_Click" />
  13:          &nbsp;
  14:          <asp:Button ID="GetList" runat="server" Text="GetList" OnClick="GetList_Click" />
  15:      </div>
  16:      <div>
  17:          <table>
  18:              <tr>
  19:                  <td>
  20:                      Select Owner
  21:                  </td>
  22:                  <td>
  23:                      <asp:DropDownList ID="dpOwner" runat="server">
  24:                      </asp:DropDownList>
  25:                  </td>
  26:              </tr>
  27:              <tr>
  28:                  <td>
  29:                      PetName
  30:                  </td>
  31:                  <td>
  32:                      <asp:TextBox ID="txtpet" runat="server"></asp:TextBox>
  33:                  </td>
  34:              </tr>
  35:              <tr>
  36:                  <td colspan="2">
  37:                      <asp:Button ID="cmdaddpet" runat="server" Text="Add Pet" 
  38:                          onclick="cmdaddpet_Click" />
  39:                  </td>
  40:              </tr>
  41:          </table>
  42:      </div>
  43:      </form>
  44:  </body>
  45:  </html>




Cs File

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.Linq;
   4:  using System.Web;
   5:  using System.Web.UI;
   6:  using System.Web.UI.WebControls;
   7:  using Presenter.Test;
   8:  using Presenter.Test.ViewInterFace;
   9:  using Test.EntityAccess;
  10:   
  11:  namespace DateControl
  12:  {
  13:      public partial class LinqTest : System.Web.UI.Page, IViewOwner, IViewPet
  14:      {
  15:          PresenterOwner _owner;
  16:          PresenterPet _pet;
  17:   
  18:          protected void Page_Load(object sender, EventArgs e)
  19:          {
  20:   
  21:              _owner = new PresenterOwner(this);
  22:              _pet = new PresenterPet(this);
  23:              if (!IsPostBack)
  24:              {
  25:                  FillOwner();
  26:              }
  27:              //  AddTestPet();
  28:              //  List<Pet> Listofpet = GetPetList();
  29:   
  30:              // // Listofpet.ForEach(c => UpdatePet(c));
  31:              //  var obj = (from c in Listofpet
  32:              //               select UpdatePet(c)).Count();
  33:   
  34:              ////  (from c in Listofpet select DeletePet(c)).Count();
  35:   
  36:          }
  37:   
  38:          protected void btnaddowner_Click(object sender, EventArgs e)
  39:          {
  40:              Owner own = new Owner();
  41:              own.Name = txtOwner.Text;
  42:              own.Age = 25;
  43:              _owner.AddOwner(own);
  44:              FillOwner();
  45:          }
  46:          protected void GetList_Click(object sender, EventArgs e)
  47:          {
  48:              _owner.GetLisofOwner();
  49:          }
  50:   
  51:          ///// <summary>
  52:          ///// Insert Pet Records
  53:          ///// </summary>
  54:          //private void AddTestPet()
  55:          //{
  56:          //    using (PetDataContext context = new PetDataContext())
  57:          //    {
  58:          //        var Listofpets = (from obj in context.Pets select obj);
  59:          //        Pet pet = new Pet();
  60:          //        pet.Birthday = DateTime.Now;
  61:          //        pet.PetName = "Test";
  62:          //        pet.Species = "Test";
  63:   
  64:   
  65:          //        context.Pets.InsertOnSubmit(pet);
  66:          //        context.SubmitChanges();
  67:          //    }
  68:          //}
  69:   
  70:          ///// <summary>
  71:          ///// GetList of Pet
  72:          ///// </summary>
  73:          ///// <returns></returns>
  74:          //protected List<Pet> GetPetList()
  75:          //{
  76:          //    List<Pet> ListOfPets;
  77:          //    using(PetDataContext db=new PetDataContext())
  78:          //    {
  79:          //        ListOfPets =(from c in db.Pets select c).ToList();
  80:          //    }
  81:          //    return ListOfPets;
  82:          //}
  83:   
  84:          ///// <summary>
  85:          ///// Update Pet Records
  86:          ///// </summary>
  87:          ///// <param name="Pet"></param>
  88:          ///// <returns></returns>
  89:          //protected bool UpdatePet(Pet Pet)
  90:          //{
  91:          //    using (PetDataContext db=new PetDataContext())
  92:          //    {
  93:          //        //var pets=(from c in db.Pets 
  94:          //        //              where c.PetName == Pet.PetName select c ).FirstOrDefault();
  95:   
  96:          //        Pet.PetName = "Test Update";
  97:   
  98:          //        db.Pets.Attach(Pet);
  99:          //        db.Refresh(System.Data.Linq.RefreshMode.KeepCurrentValues, Pet);
 100:          //        db.SubmitChanges();
 101:          //    }
 102:          //    return true;
 103:   
 104:   
 105:          //}
 106:   
 107:          ///// <summary>
 108:          ///// Delete Pet Records
 109:          ///// </summary>
 110:          ///// <param name="_Pet"></param>
 111:          ///// <returns></returns>
 112:          //protected bool DeletePet(Pet _Pet)
 113:          //{
 114:          //    using (PetDataContext db = new PetDataContext())
 115:          //    {
 116:          //        var pet=(from c in db.Pets
 117:          //                      where c.PetName==_Pet.PetName select c ).FirstOrDefault();
 118:   
 119:          //        db.Pets.DeleteOnSubmit(pet);
 120:          //        db.SubmitChanges();
 121:          //    }
 122:          //    return true;
 123:          //}
 124:   
 125:   
 126:   
 127:   
 128:          #region IViewOwner Members
 129:   
 130:          public IList<Owner> ListOfOwner
 131:          {
 132:              get;
 133:              set;
 134:          }
 135:   
 136:          public Owner CurrentOwner
 137:          {
 138:              get;
 139:              set;
 140:          }
 141:   
 142:          #endregion
 143:   
 144:          protected void cmdaddpet_Click(object sender, EventArgs e)
 145:          {
 146:   
 147:              Pet P = new Pet();
 148:              P.PetName = txtpet.Text;
 149:              P.OwnerId = Convert.ToInt32(dpOwner.SelectedValue);
 150:              P.BirthDay = new DateTime(1970,5,23);
 151:              _pet.AddPet(P);
 152:          }
 153:   
 154:          private void FillOwner()
 155:          {
 156:              _owner.GetLisofOwner();
 157:              dpOwner.DataSource = ListOfOwner;
 158:              dpOwner.DataTextField = "Name";
 159:              dpOwner.DataValueField = "Id";
 160:              dpOwner.DataBind();
 161:          }
 162:   
 163:   
 164:   
 165:          #region IViewPet Members
 166:   
 167:          public Pet Pet
 168:          {
 169:              get;
 170:              set;
 171:   
 172:          }
 173:   
 174:          public IList<Pet> ListOfPet
 175:          {
 176:              get;
 177:              set;
 178:          }
 179:   
 180:          #endregion
 181:      }
 182:  }




Here we need to inherit presenter interface so we get all property here and we can pass interface from presenter object

so presenter will call task and task communicate with model access sql and fill entity and pass to presenter and from aspx page we get result. nice structure for complex project

Monday, January 9, 2012

Custom Validation using DataAnnotationsModelValidator


Hi,

After long time I like to write some more tips on validation in MVC  3.0  because it’s very cool as using this much code not required to write in JavaScript and jquery so avoid put business logic needs to write in client side. Here I explain custom validation using loan module

Here is my Validation class 
// Comment
    public class SalaryAttributes : ValidationAttribute
    {
        private readonly int _minSalary = 0;

        public SalaryAttributes(int minSalary)
        {
            _minSalary = minSalary;
        }

        protected override System.ComponentModel.DataAnnotations.ValidationResult IsValid(object value, System.ComponentModel.DataAnnotations.ValidationContext validationContext)
        {
            if (value != null)
            {
                int data = (int)value;
                if (data < _minSalary)
                {
                    return new ValidationResult("Salary must be more than "+ _minSalary.ToString());
                }                
            }
            return ValidationResult.Success;
        }
    }
This class will check salary of person required more than pass min salary if not it will display message
Now we needs to add this validation attributes in dataanotationvalidation model
We can add using wrap other class and override GetClientValidationRules
Which contain basic rules

// Comment

public class SalaryValidator : DataAnnotationsModelValidator
    {
        int minSalary = 0;
        string errorMsg = string.Empty;

        public SalaryValidator(ModelMetadata metadata, ControllerContext context, SalaryAttributes attributes)
            : base(metadata, context, attributes)
        {
            errorMsg = attributes.ErrorMessage;
        }

        public override IEnumerable GetClientValidationRules()
        {
            ModelClientValidationRule ValidationRule = new ModelClientValidationRule();
            ValidationRule.ErrorMessage = errorMsg;
            ValidationRule.ValidationType = "Salary";
            ValidationRule.ValidationParameters.Add("minSalary", minSalary);
            return new[] { ValidationRule };
        }
    }

Now quick looks my model contain 2 class Customer and dataaccess of customer
Where I have pass min salary is 20,000 which is min salary so not allow less than this

// Comment


    public class Customer
    {
        [Required]
        public string Customers { get; set; }
        [Required]
        public string city { get; set; }
        [SalaryAttributes(20000)]
        public int Salary { get; set; }

    }


    public class DataAccess
    {
        static List lstCustomer=new List();
        public DataAccess()
        {
            lstCustomer.Clear();
            lstCustomer.Add(new Customer(){ Customers="bhavik", city="Ahmedabad", Salary=28000 });
            lstCustomer.Add(new Customer(){ Customers="sandeep", city="Ahmedabad", Salary=21000 });
            lstCustomer.Add(new Customer(){ Customers="Shumit", city="Ahmedabad", Salary=25000 });
        }

        public List getCustomer()
        {
            return lstCustomer;
        }

        public void addCustomer(Customer cust)
        {
            lstCustomer.Add(cust);
        }

    }

Now quick create customer Controllers which contain index and xreate method
Now using index and create method generate view with model customer

// Comment


  [HandleError]
    public class CustomerController : Controller
    {
        DataAccess objContex = new DataAccess();
        //
        // GET: /Customer/

        public ActionResult Index()
        {
            var Customers = objContex.getCustomer();
            return View(Customers);
        }

        public ActionResult Create()
        {
            var Customer = new Customer();
            return View(Customer);
        }

        [HttpPost]
        public ActionResult Create(Customer obj)
        {
            try
            {
                var Customer = new Customer();
                if (ModelState.IsValid)
                {
                    Customer.city = obj.city;
                    Customer.Customers = obj.Customers;
                    Customer.Salary = obj.Salary;
                    objContex.addCustomer(Customer);        
                    return View("Index");
                }
                else
                {
                    return View(obj);
                }
            }


            catch (Exception)
            {
                var Customer = new Customer();
                return View(Customer);
            }
        }

    }

Look at generated code for index and customer
// Comment

@model IEnumerable

@{
    ViewBag.Title = "Index";
}

Index

@Html.ActionLink("Create New", "Create") @foreach (var item in Model) { }

Customers

city

Salary

@Html.DisplayFor(modelItem => item.Customers)

@Html.DisplayFor(modelItem => item.city)

@Html.DisplayFor(modelItem => item.Salary)

@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
@model ASPNET_MVC3_Custom_ModelValidation.Models.Customer @{ ViewBag.Title = "Create"; }

Create

@using (Html.BeginForm()) { @Html.ValidationSummary(true)
Customer
@Html.LabelFor(model => model.Customers)
@Html.EditorFor(model => model.Customers) @Html.ValidationMessageFor(model => model.Customers)
@Html.LabelFor(model => model.city)
@Html.EditorFor(model => model.city) @Html.ValidationMessageFor(model => model.city)
@Html.LabelFor(model => model.Salary)
@Html.EditorFor(model => model.Salary) @Html.ValidationMessageFor(model => model.Salary)
}
@Html.ActionLink("Back to List", "Index")

Now run code and check how validation work

Customer Validation using DataAnnotationsModelValidator


Tuesday, November 22, 2011

additional parameters to the Json remote validtation

 

 

I have already write simple Example for Remote Attribute but I think i need to add little more in this but for basic working of remote attribute please follow my previous article where I have explain what’s remote attributes and how it will work. from given link Remote Attribute

  In Remote Validation attribute if some time we have case we need to check user input on basis of other parameter. like on registration form of some website needs to allowed user from between 18-32 age so here conditional check means range check. let me explain how we can achieve this using remote attributes. in remote attributes have property to pass AdditionalFields here we can pass as many fields as we want. suppose we want to pass one filed we need to just given value. if we need to pass more than one fields we need to given fields in coma separated like “Field1,Field2”

let check using Example

 

Here is Very Simple Model

// Comment

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Model
{
    public class UserInformation
    {
        [Required]
        [System.Web.Mvc.Remote("IsUserNameExits", "Validation")]         
        public string Name { get; set; }

        [Required] 
        public string City { get; set; }
        public string Account { get; set; }

        [Required]
        [System.Web.Mvc.Remote("AgeAllowed", "Validation", AdditionalFields = "Min,Max")]    
        public Int32 AllowedAge { get; set; }
       
    }
}

 

now look at AgeAllowed where I have given conditional formatting. I want to make age required between Min and max value. now look at my View where

I have display very simple view

// Comment

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "signupform" }))
{
  <div>
  Temp: @TempData["TestTemp"]
  ViewData: @ViewData["TestTemp"]
  </div>  
    
    
    @Html.ValidationSummary(true)
    <fieldset> <legend>UserInformation</legend> <div class="editor-label">@Html.LabelFor(model => model.Name) </div> <div class="editor-field">@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label">@Html.LabelFor(model => model.City) </div> <div class="editor-field">@Html.EditorFor(model => model.City) @Html.ValidationMessageFor(model => model.City) </div> <div class="editor-field">@Html.DropDownList("dplist",(SelectList) ViewBag.DpList) @Html.TextBox("txtbox") </div> <div class="editor-label">@Html.ValidationMessageFor(model => model.AllowedAge) </div> <div class="editor-field">@Html.EditorFor(model => model.AllowedAge) <input value="18" type="hidden" name="Min"> <input value="32" type="hidden" name="Max"> </div> <p> <input value="Save" type="submit"> <input onclick="javascript:AjaxSave();" value="AjaxSave" type="button"> </p> </fieldset>
}

Here I have taken min and max as hidden fields. if your project required to get value from database you can define value in model and get value from database.  

now look at one Controllers I have create for Validation

// Comment


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

namespace MvcApplication1.Controllers
{
    public class ValidationController : Controller
    {
        //
        // GET: /Validation/

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult IsUserNameExits(string Name)
        {
            
            if (Name == "Bhavik")
            {
               return Json("Sorry UserName Already Taken", JsonRequestBehavior.AllowGet);    

            }
            else
            {               
                return Json(true, JsonRequestBehavior.AllowGet);    
            }

            
        }
        //
        public JsonResult AgeAllowed(Int32 AllowedAge, Int32 Min, Int32 Max)
        {
            //
            if (AllowedAge > Max || AllowedAge < Min)
            {
                //
                return Json("Sorry Age requirted beetween " + Min.ToString() + "-" + Max.ToString(), JsonRequestBehavior.AllowGet);    
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet);    
            }
        }

    }
}

 

 

now run and check

 

Here is output age allowed between 18-32 age.


Monday, November 21, 2011

How to postback on index change of ASP.net MVC dropdownlist

 

 

Now day when I search related to Mvc 3.0. I have found Question So many forums that how to get data on basis of dropdown value change. suppose I have dropdown for country when I change value from country  drop down I need other info display in view which need to collect from sql database. now let’s play with this question

 

I have create one simple view

which contain only one drop down

// Comment

@{
    ViewBag.Title = "Index";
}

Index

Select List:@Html.DropDownList("dplist", (SelectList)ViewBag.DpList)

 

now let’s look my controller

// Comment

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

namespace MvcApplication1.Controllers
{
    public class FilterController : Controller
    {
        //
        // GET: /Filter/

        public ActionResult Index()
        {
            initilization();
            return View();
        }
        public void initilization()
        {
            List LiList = new List();
            AddItemInlist("One", 1, LiList, false);
            AddItemInlist("Two", 2, LiList, false);
            AddItemInlist("Three", 3, LiList, true);
            AddItemInlist("Four", 4, LiList, false);
            AddItemInlist("Five", 5, LiList, false);
            ViewBag.DpList = new SelectList(LiList, "Value", "Text");  
        }

        public void AddItemInlist(string Key, Int32 value, List addtolist, bool IsSelected)
        {
            SelectListItem Li = new SelectListItem();
            Li.Text = Key;
            if (IsSelected)
            {
                Li.Selected = true;
            }
            Li.Value = value.ToString();
            addtolist.Add(Li);

        }

        public ActionResult GetData(int  id)
        {
            //in dplist you will get vaue of dropdown value 
            //on basis of this you can create your logic
             List LiList = new List();

            
             AddItemInlist("Apple", 1, LiList, false);
             AddItemInlist("Bannan", 2, LiList, false);
             
             return Json(LiList,JsonRequestBehavior.AllowGet); 
        }

    }
}

 

 

here main point is that I have create on action getdata using this I am getting data when I change dropdown value

here is Java script which will call when I change dropdown

// Comment

<script type="text/javascript">
    $(document).ready(function () {

        $("#dplist").change(function () {



            var Url = '/Filter/GetData/' + parseInt($(this).val());


            $.ajax({
                url: Url,
                type: 'GET',
                dataType: 'json',
                contentType: 'application/json',
                success: function (data) {                  
                    data = data
                    $.each(data, function (key, value) {                      
                    //get each value
                        alert(value.Text);
                        alert(value.Value);
                    });



                }

            });

        });

    });
 
</script> 
Here is My Output

Saturday, November 19, 2011

ViewBag, ViewData, or TempData in ASP.NET MVC 3

 

 

In Mvc This 3 object work like property and use in view and controller.  basic use is get and pass value means communication between  view controller. using this you can get or set chuck amount of data.

like here is Example

// Comment
viewdata["Name"]="Bhavik Solucky";
viewbag.Name="Bhavik Solucky"; 
tempdata["Name"]="Bhavik Solucky";

 


now here I have one view which display this value


// Comment
Temp: @TempData["Name"]
ViewData: @ViewData["["Name"];"]
viewbag:viewbag.Name;
now when we come this view all 3 variable display value

but basic difference of all 3 variable is that if you want to redirect from one view to other view then tempdata will contain value and other view doesn’t contain any detail.


suppose redirect from home view to customer view then tempdata contain value but viewbag and view data become null


more detail check this link :http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications

so when you know redirect request that time temp data is very useful

Tuesday, November 15, 2011

Multi submit button on Single Form Asp.net Mvc 3.0

 

 

In Asp.net we have practice to use one submit button per one form and form method type in most case we have taken post and action method will firer. Now suppose you have scenario where you need to add more submit button in single form how it will work. Do you have any idea? Here role of ActionNameSelectorAttribute“ will come.

Here I explain in Mvc 3.0 how we will take multi Submit Button

Let’s Look My Very Simple View

 

 

   1:  @using (Html.BeginForm("Action", "Home")) { 
   2:    <input type="submit" name="create" value="Create" />
   3:    <input type="submit" name="read" value="Read" />
   4:    <input type="submit" name="update" value="Update" />
   5:    <input type="submit" name="delete" value="Delete" />
   6:   } 

 


I have taken Simple Class


   1:   public class HttpParamActionAttribute : ActionNameSelectorAttribute
   2:      {
   3:          public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
   4:          {
   5:              if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
   6:                  return true;
   7:   
   8:              if (!actionName.Equals("Action", StringComparison.InvariantCultureIgnoreCase))
   9:                  return false;
  10:   
  11:              var request = controllerContext.RequestContext.HttpContext.Request;
  12:              return request[methodInfo.Name] != null;
  13:          }
  14:      }




 


Now look My Controller


   1:    public class HomeController : Controller
   2:      {
   3:          //
   4:          // GET: /Home/
   5:   
   6:          public ActionResult Index()
   7:          {
   8:    
   9:              return View();
  10:          }       
  11:        
  12:          [HttpPost]
  13:          public ActionResult Index(UserInformation u)
  14:          {     
  15:              return View();
  16:          } 
  17:   
  18:          [HttpParamAction]
  19:          [HttpPost]
  20:          public ActionResult Create()
  21:          {
  22:              return View("");
  23:          }
  24:   
  25:          [HttpParamAction]
  26:          [HttpPost]
  27:          public ActionResult Read()
  28:          {
  29:              return View("");
  30:          }
  31:   
  32:          [HttpParamAction]
  33:          [HttpPost]
  34:          public ActionResult Update()
  35:          {
  36:              return View("");
  37:          }
  38:   
  39:          [HttpParamAction]
  40:          [HttpPost]
  41:          public ActionResult Delete()
  42:          {
  43:              return View("");
  44:          }
  45:   
  46:   
  47:      }



 


 


Now in Above Controller I have specified HttpParamAction in all method which will call as per my view. now when user press any button IsValidName  method will call and if Action and method name will not match it will create new post request and firer that method as per method name.

so using this way we can work with Multi submit button on Single Form Asp.net Mvc 3.0.

let me know if you need more help on this.   

Friday, November 11, 2011

Apply conditional formatting

// Comment
private void attach_RegionCounties(RegionCounty entity)
  {
   this.SendPropertyChanging();
   entity.County = this;
  }
  
  private void detach_RegionCounties(RegionCounty entity)
  {
   this.SendPropertyChanging();
   entity.County = null;
  }
  
  private void attach_Buildings(Building entity)
  {
   this.SendPropertyChanging();
   entity.County = this;
  }
  
  private void detach_Buildings(Building entity)
  {
   this.SendPropertyChanging();
   entity.County = null;
  }
  
  private void attach_Schedules(Schedule entity)
  {
   this.SendPropertyChanging();
   entity.County = this;
  }