Sunday, June 19, 2011

ASP.Net simple things

To update DB with Datetime format using C# code

DateTime StartDate = DateTime.Parse(txtStartDate.Text, System.Globalization.CultureInfo.InvariantCulture);

Monday, June 6, 2011

Simple but time consuming things

  1. The HttpPost was not called when hitting  submit button in MVC view
   This was fixed by including(in some cases)

   <%using (Html.BeginForm())
          {%>


 2. The Request.Files  empty issue
   This will be recovered by using mutipart post method
    
    <%using (Html.BeginForm("Fileupload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
          {%>

//Action Name, Controller in begin form method 

 3. To ensure tat end date is greater than the start date using jquery concept. The following is the code




$('#StartDate').datepicker().change(function () {
            $('#EndDate').datepicker("destroy");//Here destroying the dates
            $('#EndDate').datepicker({ minDate: new Date($("#StartDate").val()), maxDate: "+1M +10D" });
//By here we enabling the date greater than start date we selected
        });
4. Converting default Datetime format to required datetime format in MVC when displaying
      First we need to get tat value in another datetime variable and then need to convert it to string for required format as like below:


<%var Startdate=Convert.ToDateTime(item.LeaveStartDate);%>
            <%=Startdate.ToString("dd/MM/yyyy")%>

Adding More than one File Upload control by button event

The steps are:
1. At first as usual we need to create entity for that and then to create an strongly typed dataset using xsd
2. In the repository to save the files to DB we need to code the following:

public static void InsertFile(string FileName)
        {
            using (FilesTableAdapter ta = new FilesTableAdapter())
            {
                if (FileName != null)
                {
                    ta.InsertFile(FileName);
                }
            }
        }

3. In controller the following code is done to insert the file
Also shld add the system.io header file

[HttpGet]
        public ActionResult Fileupload()
        {
            return View();
        }

[HttpPost]
        public ActionResult Fileupload(FormCollection frm, string save)
//Here save is the value of the “Submit” button
        {
            if (save.Equals("save")==true)
            {       
                foreach (string file in Request.Files)
// Request.Filesรจis the pre defined function
                {
                    var postedfile = Request.Files[file];
                    if (postedfile.ContentLength != 0)
                    {
                    postedfile.SaveAs(Server.MapPath("~/Files/") + Path.GetFileName(postedfile.FileName));
                    string Filename =Path.GetFileNameWithoutExtension(postedfile.FileName) + Path.GetExtension(postedfile.FileName);
// Path.GetFileName(),GetFileNameWithoutExtension(),GetExtension are the built-in methods for retrieving the file name
                     FileRepository.InsertFile(Filename);                       
//As we know “InsertFile” is an DB function 
                    }                   
                }
                return View();
              }
            return View();
        }

4. Finally in View,

<%using (Html.BeginForm("Fileupload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
          {%>
    <script type="text/javascript" language="javascript">

        var Filecount = 0;
        function AddFileControl() {
            if (Filecount <= 4) {
                var div = document.createElement('DIV');
                div.innerHTML = '<input id="file' + Filecount + '"name="file' + Filecount + '"type="file" style=width:50%/>' + " " + " " + " " + '<input id="button' + Filecount + '"type="button"''value="Remove" onclick="RemoveFileControl(this)" style=widht:"15%" />' + '<br/>';
                div.style.padding = "0.5em";
                document.getElementById("FileControl").appendChild(div);
                Filecount++;
            }
            else
                alert('Only 5 files can be uploaded');
        }


        function RemoveFileControl(div) {
            document.getElementById("FileControl").removeChild(div.parentNode);
            Filecount--;
        }
       
    </script>

    <table>
    <tr>
    <td>
    <div id="FileControl"></div>
    <input type="button" name="AddMoreFiles" value="AddMoreFiles" onclick="AddFileControl()" />
    <script type="text/javascript" language="javascript">
        AddFileControl();
    </script>
    </td>
    </tr>
    <tr>
    <td>
    <input type="submit" value="save" name="save"/>   
    </td>   
    </tr>
    </table>  
    <% } %>


Thursday, June 2, 2011

Dynamic Jquery Grid from DB

I was trying to bind the DB table to the Jquery grid but finally i failed

wat i did was
1. First i created Entity for the data and created .XSD file

2. And in Controller i did the following to retrive the DB table
public JsonResult GetEmp()
{

List<EmployeelEntity> result = new List<EmployeelEntity>();
//List<EmployeelEntity> empid = new List<EmployeelEntity>();
//List<EmployeelEntity> empname = new List<EmployeelEntity>();
//List<EmployeelEntity> empdesig = new List<EmployeelEntity>();
{
using (EmployeeTableAdapter ta = new Repository.EmployeeTableAdapters.EmployeeTableAdapter())
{
using (Employee.EmployeeDataTable dt = ta.SelectQuery())

{
foreach (Employee.EmployeeRow row in dt)
{
EmployeelEntity EE = new EmployeelEntity();
EE.EmpID = row.EmpID;

//empid.Add(EE);
EE.Name = row.Name;
//empname.Add(EE);
EE.Designation = row.Designation;
//empdesig.Add(EE);
result.Add(EE);
}
}
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}

3. In view i did like this
 <table id="Employeelist" class="scroll"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>

<script language="javascript" type="text/javascript">
alert("script");
$(document).ready(function(){
alert("Inside");
$("#Employeelist").jqGrid({
url:'/Home/GetEmp/',
datatype:'json',
colNames:['EmpId','Name','Designation'],
colModel:[
              { name: 'EmpId', index: 'EmpId', width: 55, align: 'left' },
              { name: 'Name', index: 'Name', width: 250 },
              { name: 'Designation', index: 'Designation', width: 250, align: 'right'}],
pager:jQuery('#pager'),
rowNum:3,
caption:
'Employee Details'

});
});
</script>


Conclusion:
 But am not able to get the result the Jquery grid alone is displaying but i was not able to bind data in tat
 If anyone knows help me out of this

Dynamic Checkbox for the Data in DB table

We are going to create checkboxes for the items in DB

1. First we need to create the entity for them and create .xsd file

2. Then in city repository we have to retrive the data from table as follows:
public static List<CitiesEntity> GetCitylist()
{
List<CitiesEntity> result = new List<CitiesEntity>();

using (CitiesTableAdapter ta = new CitiesTableAdapter())
{

using (City.CitiesDataTable dt = ta.GetCities())
{
foreach (City.CitiesRow row in dt)
{
CitiesEntity CE = new CitiesEntity();
CE.Cities = row.Cities;
result.Add(CE);
}
return result;
}
}
}

3. Next in Controller we need to call the repository functions as usual
[HttpGet]

public ActionResult GetCheckBox()
{
List<CitiesEntity> Cities = CityRepository.GetCitylist();
ViewData["Chkitems"] = Cities;//Stores list of cities for further reference

return View();
}
 
[HttpPost]

public ActionResult GetCheckBox(FormCollection frm)
{
List<CitiesEntity> Cities = CityRepository.GetCitylist();
ViewData["Chkitems"] = Cities;//Stores list of cities for further reference
int j = Cities.Count;
List<string> cbsource = new List<string>();
string source = "";
for (int i = 0; i <= j; i++)
{
string key = "cbxid" + i.ToString();
if (frm[key] != null)

{
source += frm[key].ToString() + ",";
ViewData["src"] = "You have selected : " + source +".";

//Total datas which have being selected
}
}
return View();
}

4. Here in View we need to import the header files of models and repository as like:<%@ Import Namespace="Jquery.Models"%>
<%@ Import Namespace="Jquery.Repository"%>

then in Html.BeginForm we have to write the following code to display the datas with checkbox<% using(Html.BeginForm())
{ %>

<%int i=0;%>
<%foreach (var item in (IEnumerable<CitiesEntity>)

ViewData["Chkitems"])//Uses the items from DB
{%>
<input type="checkbox" name="cbxid<%=i.ToString()%>" id="cbxid<%=i.ToString()%>" value="<%=item.Cities%>" />

<%=item.Cities%>
<%--<br />--%>
<%i++;%>
<%}%>
<br />

<br />
<br />
<input type="submit" name="Submit" value="Submit" />
<%if (ViewData["src"] != null) //If user selects something
{%>
<%=ViewData["src"]%>
<%}%>
<%}%>

Auto Complete Textbox in MVC

Here is Auto complete textbox for city names witth reference to the cities stored in particular DB

The following are the steps to follow:

1. Define the Entity for the "city" field in the Repository folder

2. Next we need to add the Dataset for the DB with the apprpriate query to retrive data for the autocomplete textbox

3. In repository we have to write the code to connect with database
Here is the code:
public static List<CityEntity> GetCity(string TNCity)//Text in the textbox as parameter which will be passed as an variable in Stored proc.
{
List<CityEntity> result = new List<CityEntity>();
using (tblCitiesTableAdapter ta = new tblCitiesTableAdapter())
{
using (City.tblCitiesDataTable dt = ta.GetCityName(TNCity))
{
foreach (City.tblCitiesRow row in dt)
{
CityEntity CE = new CityEntity();
CE.City = row.City;
result.Add(CE);
}
return result;
}
}
}


4. In controller we have to cal the repository function
//This is called in master page action link
public ActionResult Cities()
{
return View();
}

//This is called in autocomplete function of the view
public ActionResult City(string q)
{
try{
string[] City = GetCity(q);

return Content(string.Join("\n", City));
}
catch( Exception ex)
{
throw ex;
}
}

//This is called in the previous function

public string[] GetCity(string TNCity)
{
try{
List<CityEntity> resultCity = CityRepository.GetCity(TNCity);

string[] src = new string[resultCity.Count];
int i = 0;
foreach (CityEntity cct in resultCity)
{
src[i] = cct.City;
i++;
}
return src;
}
catch(Exception e)
{
throw e;
}
}

5.the final step is view in which we need to give the URL for autocomplete action
<%=Html.TextBox("txtCity")%>

<script language="javascript" type="text/javascript">$(
$(function () { '#txtCity').autocomplete('<%=Url.Action("City","Home") %>',

autoFill:true
});
});
</script>