Tuesday, 30 August 2016

MVC5 CRUD OPERATION STEP BY STEP

Step 1:
Create a Model class———-
public class Booking
{
public virtual int Id { get; set; }
public virtual string HallName { get; set; }
public virtual DateTime bookDate { get; set; }
public virtual string fromtime { get; set; }
public virtual string toTime { get; set; }
public virtual int people { get; set; }
public virtual string status { get; set; }
}
public class ResultObject
{
public int ResultID { get; set; }
public string ResultMessage { get; set; }
public Object Obj { get; set; }
public string Code { get; set; }
}
public class PagedBookingModel
{
public int TotalRows { get; set; }
public IEnumerable Booking { get; set; }
public int PageSize { get; set; }
}
Step 2: Create a Contex of EntityFrmework to access database–
public class BookHallContext : DbContext
{
public BookHallContext() : base(“name=BookHallContext”)
{
}
public System.Data.Entity.DbSet Bookings { get; set; }
}
Step 3: Create a dataAccess Layer—————–
public class BookDataAccess
{
public BookDataAccess() { }
public BookHallContext db = new BookHallContext();
//public DataTable GetDataTable(string commandText)
//{
// // get a configured DbCommand object
// DbCommand comm = GenericDataAcccess.CreateCommand();
// // set the stored procedure name
// comm.CommandText = commandText;
// // execute the stored procedure and return the results
// return GenericDataAcccess.ExecuteSelectCommand(comm);
//}
public IEnumerable GetBookingPage(int pageNumber, int pageSize, string searchCriteria)
{
if (pageNumber m.HallName)
.Skip((pageNumber – 1) * pageSize)
.Take(pageSize)
.ToList();
}
public int CountAllHall()
{
return db.Bookings.Count();
}
public void Dispose()
{
db.Dispose();
}
public Booking GetBookingDetail(int mCustID)
{
return db.Bookings.Where(m => m.Id == mCustID).FirstOrDefault();
}
public bool AddBooking(Booking book)
{
try
{
db.Bookings.Add(book);
db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool UpdateEmployee(Booking bk)
{
try
{
Booking data = db.Bookings.Where(m => m.Id ==bk.Id).FirstOrDefault();
data.HallName = bk.HallName;
data.bookDate = bk.bookDate;
data.fromtime = bk.fromtime;
data.toTime = bk.toTime;
data.people = bk.people;
db.SaveChanges();
return true;
}
catch (Exception mex)
{
return false;
}
}
public bool DeleteBooking(int mCustID)
{
try
{
Booking data = db.Bookings.Where(m => m.Id == mCustID).FirstOrDefault();
db.Bookings.Remove(data);
db.SaveChanges();
return true;
}
catch (Exception mex)
{
return false;
}
}
public ResultObject InsertBookInfo(Booking binfo)
{
string error;
ResultObject resObj = new ResultObject();
SqlConnection con = new SqlConnection(GlobalClass.connection);
SqlCommand cmd = new SqlCommand(“”, con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.CommandText = @”Insert into Bookings( bookDate,HallName,fromtime,toTime,people) Values(‘” + (binfo.bookDate).ToString(“yyyy/MM/dd”) + “‘,'” + binfo.HallName + “‘,'” + binfo.fromtime + “‘,'” + binfo.toTime + “‘,'” + binfo.people + “‘)”;
int result = -1;
try
{
result = cmd.ExecuteNonQuery();
}
catch
{
result = -1;
}
resObj.ResultID = result;
if (result > 0)
{
resObj.ResultMessage = “Data Saved Successfully”;
resObj.Obj = GetBookingInfoList();
}
else
{
resObj.ResultMessage = “Data Not Saved”;
}
con.Close();
return resObj;
}
public ResultObject UpdateBookInfo(Booking binfo)
{
string error;
ResultObject resObj = new ResultObject();
SqlConnection con = new SqlConnection(GlobalClass.connection);
SqlCommand cmd = new SqlCommand(“”, con);
cmd.CommandType = CommandType.Text;
con.Open();
cmd.CommandText = @”Update Bookings set bookDate='” + binfo.bookDate.ToString(“yyyy/MM/dd”) + “‘,HallName='” + binfo.HallName + “‘,fromtime='” + binfo.fromtime + “‘,toTime='” + binfo.toTime + “‘,people='” + binfo.people + “‘ where Id='”+binfo.Id+”‘)”;
int result = -1;
try
{
result = cmd.ExecuteNonQuery();
}
catch
{
result = -1;
}
resObj.ResultID = result;
if (result > 0)
{
resObj.ResultMessage = “Data Updated Successfully”;
resObj.Obj = GetBookingInfoList();
}
else
{
resObj.ResultMessage = “Data Not Saved”;
}
con.Close();
return resObj;
}
public List GetBookingInfoList()
{
List objList = new List();
DataTable dt = GetAllBookingInfo();
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
objList.Add(new Booking
{
Id = int.Parse(dt.Rows[i]["Id"].ToString()),
bookDate = Convert.ToDateTime(dt.Rows[i]["bookDate"]),
fromtime = dt.Rows[i]["fromtime"].ToString(),
toTime = dt.Rows[i]["toTime"].ToString(),
HallName = dt.Rows[i]["HallName"].ToString(),
people = Int32.Parse(dt.Rows[i]["people"].ToString())
});
}
}
return objList;
}
public DataTable GetAllBookingInfo()
{
DataTable tbl = new DataTable();
SqlConnection con = new SqlConnection(GlobalClass.connection);
SqlCommand cmd = new SqlCommand("", con);
cmd.CommandType = CommandType.Text;
cmd.CommandText = @"Select Id,bookDate,HallName,fromtime,toTime,people from Bookings";
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(tbl);
return tbl;
}
Step 4: Create a Controller
public class BookingController : Controller
{
public BookHallContext db = new BookHallContext();
// GET: /Booking/
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
// GET: /Booking/Details/5
public ActionResult LoadBookInfo()
{
BookDataAccess acess = new BookDataAccess();
return Json(acess.GetBookingInfoList());
}
public ActionResult InsertBookInfo(Booking obj)
{
BookDataAccess acess = new BookDataAccess();
return Json(acess.InsertBookInfo(obj));
}
public ActionResult UpdateBookInfo(Booking obj)
{
BookDataAccess acess = new BookDataAccess();
return Json(acess.UpdateBookInfo(obj));
}
}
Step 5: Create a view—————–
@{
//WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
//grid.Bind(Model.Bookings,
// autoSortAndPage: false,
// rowCount: Model.TotalRows
//);
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
$(document).ready(function () {
// alert(“ok”);
$(“#dvLoading”).hide();
LoadInfo();
$(“#btnSave”).click(function () {
$(“#dvLoading”).dialog();
$(“#lblInfo”).html(”);
var bookInfo = {
“HallName”: $(“#txtHallName”).val(),
“bookDate”: $(“#txtbookDate”).val(),
“fromtime”: $(“#txtfromtime”).val(),
“toTime”: $(“#txttoTime”).val(),
“people”: $(“#txtPeople”).val(),
“Id”: $(“#txtId”).val()
};
var Method = ”;
if ($(“#btnSave”).val() == ‘Update’) {
Method = “UpdateBookInfo”;
}
else {
Method = “InsertBookInfo”;
}
$.ajax({
type: “post”,
url: “/Booking/” + Method,
dataType: “JSON”,
contentType: “application/json;charset=utf-8”,
data: JSON.stringify({ “obj”: bookInfo }),
//data: JSON.stringify({ “_pinfo”: patientInfo }),
success: function (response) {
$(“#dvLoading”).hide();
// var response = data.d;
//
if (response.ResultID != ‘-1’) {
$(“#lblInfo”).html(‘‘ + response.ResultMessage + ‘‘);
ClearField();
BindTable(response.Obj);
$(“#btnSave”).val(“Save”);
}
else {
$(“#lblInfo”).html(‘‘ + response.Code + ‘‘);
}
},
error: function (a, b, c) {
$(“#dvLoading”).hide();
alert(a + ‘..’ + c.statusCode);
}
});
});
function LoadInfo() {
// alert(“Load info mcalled”);
$(“#dvLoading”).show();
$.ajax({
type: “POST”,
url: “/Booking/LoadBookInfo”,
contentType: ‘application/json; charset=utf-8’,
dataType: ‘json’,
cache: false,
success: function (result) {
$(“#dvLoading”).hide();
//var response = result.d;
BindTable(result)
// console.log(response);
},
error: function (xhr, textStatus, errorThrown) {
$(“#dvLoading”).hide();
// alert(xhr.responseText);
alert((“Error thrown ” + errorThrown + “Status: ” + xhr.status));
console.log(xhr + textStatus + errorThrown);
}
});
}
function BindTable(data) {
$(“#tbldata tr:gt(0)”).remove();
var content = ”;
$.each(data, function (i, quality) {
content += ‘
‘ + quality.HallName + ‘ ‘ + quality.bookDate + ‘ ‘ + quality.fromtime + ‘ ‘ + quality.toTime + ‘ ‘ + quality.people + ‘ ‘ + quality.status + ‘ ‘ + quality.Id + ‘
‘;
});
console.log(content);
$(“#tbldata”).append(content);
}
$(“#tbldata”).on(‘click’, “tr:gt(0)”, function () {
var url = $(this).attr(‘href’);
$(“#popdialog”).dialog({
title: ‘Add New Booking’,
autoOpen: false,
resizable: false,
height: 500,
width: 400,
show: { effect: ‘drop’, direction: “up” },
modal: true,
draggable: true,
open: function (event, ui) {
$(this).load(url);
//alert(Id);
},
close: function (event, ui) {
$(this).dialog(‘close’);
}
});
var Id = $(this).find(“td:eq(6)”).text();
$(“#txtHallName”).val($(this).find(“td:eq(0)”).text());
$(“#txtbookDate”).val($(this).find(“td:eq(1)”).text());
$(“#txtfromtime”).val($(this).find(“td:eq(2)”).text());
$(“#txttoTime”).val($(this).find(“td:eq(3)”).text());
$(“#txtpeople”).val($(this).find(“td:eq(4)”).text());
$(“#txtId”).val($(this).find(“td:eq(6)”).text());
$(“#btnSave”).val(“Update”);
$(“#popdialog”).dialog(‘open’);
return false;
});
function ClearField() {
$(“#txtHallName”).val(”),
$(“#txtbookDate”).val(”),
$(“#txtfromtime”).val(”),
$(“txttoTime”).val(”),
$(“#txtpeople”).val(”),
$(“#txtId”).val(”)
}
});
.CSSTableGenerator {
margin: 0px;
padding: 0px;
width: 100%;
border: 1px solid #000000;
}
.CSSTableGenerator table {
border-collapse: collapse;
border-spacing: 0;
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
.CSSTableGenerator tr:nth-child(odd) {
background-color: #aad4ff;
}
.CSSTableGenerator tr:nth-child(even) {
background-color: #ffffff;
}
.CSSTableGenerator td {
vertical-align: middle;
border: 1px solid #000000;
border-width: 0px 1px 1px 0px;
text-align: left;
padding: 4px;
font-size: .8em;
font-family: Arial;
font-weight: normal;
}
.CSSTableGenerator tr:last-child td {
border-width: 0px 1px 0px 0px;
}
.CSSTableGenerator tr td:last-child {
border-width: 0px 0px 1px 0px;
}
.CSSTableGenerator tr:last-child td:last-child {
border-width: 0px 0px 0px 0px;
}
.CSSTableGenerator tr:first-child td {
background-color: #005fbf;
border: 0px solid #000000;
text-align: center;
border-width: 0px 0px 1px 1px;
font-size: .8em;
font-family: Arial;
font-weight: bold;
color: #ffffff;
}
.CSSTableGenerator tr:first-child td:first-child {
border-width: 0px 0px 1px 0px;
}
.CSSTableGenerator tr:first-child td:last-child {
border-width: 0px 0px 1px 1px;
}
@*
Please wait.......
*@
HallName
BookDate
From Time
To Time
People
ID
HallNameBookDateFromTimeToTimePeopleID
$(document).ready(function () {
$(“.inputdate”).datepicker({ dateFormat: “yy-mm-dd” });
// $(“.inputtime”).timespinner();
});
====================================File Upload=========================================
public class NewsController : Controller
{
private WebAppDb db = new WebAppDb();
//
// GET: /News/
public ActionResult Index()
{
var post = db.Posts.OrderByDescending(d => d.PublishDate);
return View(post.ToList());
}
//
// GET: /News/List/
[Authorize]
public ActionResult List()
{
var post = db.Posts.OrderByDescending(d => d.PublishDate);
return View(post.ToList());
}
//
// GET: /News/Create/
[Authorize]
public ActionResult Create()
{
return View();
}
[Authorize]
[HttpPost]
public ActionResult Create(BlogPost newpost, HttpPostedFileBase file)
{
if(file != null && file.ContentLength > 0){
string GetFileName = Path.GetFileName(file.FileName);
var ServerPath = Path.Combine(Server.MapPath(“~/Content/Uploads/”), file.FileName);
file.SaveAs(ServerPath);
newpost.Image = “/Content/Uploads/” + file.FileName;
}
if(ModelState.IsValid){
db.Posts.Add(newpost);
db.SaveChanges();
return RedirectToAction(“List”);
}
return View(newpost);
}
//
// GET: /News/Edit/
[Authorize]
public ActionResult Edit(int id = 0)
{
var post = db.Posts.Find(id);
return View(post);
}
[Authorize]
[HttpPost]
public ActionResult Edit(BlogPost post, HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
string GetFileName = Path.GetFileName(file.FileName);
var ServerPath = Path.Combine(Server.MapPath(“~/Content/Uploads/”), file.FileName);
file.SaveAs(ServerPath);
post.Image = “/Content/Uploads/” + file.FileName;
}
if (ModelState.IsValid)
{
db.Entry(post).State = System.Data.EntityState.Modified;
db.SaveChanges();
return RedirectToAction(“List”);
}
return View(post);
}
//
// GET: /News/Delete/
[Authorize]
public ActionResult Delete(int id = 0)
{
BlogPost post = db.Posts.Find(id);
if(post == null){
return HttpNotFound();
}
return View(post);
}
[Authorize]
[HttpPost, ActionName(“Delete”)]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id = 0)
{
BlogPost post = db.Posts.Find(id);
db.Posts.Remove(post);
db.SaveChanges();
return RedirectToAction(“List”);
}
}
Create——————————————————————-
@model NGO_Project.Models.BlogPost
@{
ViewBag.Title = “Create News”;
Layout = “~/Views/Shared/_LayoutAdmin.cshtml”;
}
@*@section Sidebar{

  • @Html.ActionLink(“Back to List”, “list”)

  • }*@
    @using (Html.BeginForm(“Create”, “News”,FormMethod.Post, new { @class = “col-md-10 center-margin”, enctype = “multipart/form-data” }))
    {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.LabelFor(model => model.Title)
    @Html.EditorFor(model => model.Title)
    @Html.ValidationMessageFor(model => model.Title, null, new { @class = “parsley-error-list” })
    @Html.LabelFor(model => model.Image)



    @Html.LabelFor(model => model.Description)
    @Html.TextAreaFor(model => model.Description, new { @class = “textarea-no-resize”, style = “margin: 0px; height: 200px;” })
    @Html.ValidationMessageFor(model => model.Description, null, new { @class = “parsley-error-list” })
    @Html.HiddenFor(model => model.PublishDate, new { Value = @DateTime.Now })
    }
    @section Scripts {
    @Scripts.Render(“~/bundles/jqueryval”)
    }
    Edit————————————————————————————-
    @model NGO_Project.Models.BlogPost
    @{
    ViewBag.Title = “Edit News”;
    Layout = “~/Views/Shared/_LayoutAdmin.cshtml”;
    }
    @using (Html.BeginForm(“Edit”, “News”,FormMethod.Post, new { @class = “col-md-10 center-margin”, enctype = “multipart/form-data” }))
    {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.LabelFor(model => model.Title)
    @Html.EditorFor(model => model.Title)
    @Html.ValidationMessageFor(model => model.Title, null, new { @class = “parsley-error-list” })
    @Html.LabelFor(model => model.Image)



    @Html.LabelFor(model => model.Description)
    @Html.TextAreaFor(model => model.Description, new { @class = “textarea-no-resize”, style = “margin: 0px; height: 200px;” })
    @Html.ValidationMessageFor(model => model.Description, null, new { @class = “parsley-error-list” })
    @Html.HiddenFor(model => model.Image, new { Value = @Model.Image })
    @Html.HiddenFor(model => model.PublishDate)
    }
    @section Scripts {
    @Scripts.Render(“~/bundles/jqueryval”)
    }
    —————————————————————–Delete————————————-
    @model NGO_Project.Models.BlogPost
    @{
    ViewBag.Title = “Delete”;
    ViewBag.Subheading = “Are you sure you want to delete this?”;
    Layout = “~/Views/Shared/_LayoutAdmin.cshtml”;
    }
    @using (Html.BeginForm(“Delete”, “News”,FormMethod.Post, new { @class = “col-md-10 center-margin” }))
    {
    @Html.AntiForgeryToken()
    @Html.LabelFor(model => model.Title)
    @Html.DisplayFor(model => model.Title)
    @Html.LabelFor(model => model.PublishDate)
    @Html.DisplayFor(model => model.PublishDate)
    @Html.LabelFor(model => model.Image)
    @Html.LabelFor(model => model.Description)
    @Html.DisplayFor(model => model.Description)
    }
    Index———————————————————————-
    @model IEnumerable
    @{
    ViewBag.Title = “News | NGO Web App”;
    ViewBag.Page = “News”;
    }
    @foreach (var item in Model)
    {

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

    @Html.DisplayFor(modelItem => item.PublishDate) @if (item.Image != null)
    { item.Image)” alt=”Image” width=”113″>}
    @Html.Raw(item.Description)

    Thursday, 25 August 2016

    Show Datepicker into TextBox in asp.net MVC5

    By following the steps below easily showing datepicker in mvc5 :


    Step 1:

    In Bundle.config fileinside App_start folder……………
    Type the following with script
    public static void RegisterBundles(BundleCollection bundles)
    {
    bundles.Add(newScriptBundle(“~/bundles/jquery”).Include(
    “~/Scripts/jquery-{version}.js”));
    // Use the development version of Modernizr to develop with and learn from. Then, when you’re
    // ready for production, use the build tool athttp://modernizr.com to pick only the tests you need.
    bundles.Add(newScriptBundle(“~/bundles/modernizr”).Include(
    “~/Scripts/modernizr-*”));
    bundles.Add(newScriptBundle(“~/bundles/bootstrap”).Include(
    “~/Scripts/bootstrap.js”,
    “~/Scripts/respond.js”));
    bundles.Add(new StyleBundle(“~/Content/css”).Include(
    “~/Content/bootstrap.css”,
    “~/Content/site.css”));
    }


    Step 2:
    In view page ……

    @Html.TextBox(“datepicker”, “”, new { @class = “form-control” })

    @Html.TextBox(“datepicker2”, “”, new { @class = “form-control” })
    $(‘#datepicker2’).datepicker(
    {
    beforeShowDay: function (date) {
    // var Highlight = SelectedDates[date];
    var hilight = [true, ”];
    return hilight;
    }
    }
    );
    //To disable specific dates……..
    var activeDays = [1, 4, 10, 21, 22, 23, 27, 28, 30];
    $(‘#datepicker’).datepicker(
    {
    beforeShowDay: function (date) {
    var hilight = [false, ”];
    if (activeDays.indexOf(date.getDate()) > -1) {
    hilight = [true, ‘isActive’];
    }
    return hilight;
    }
    }
    );



    Tuesday, 23 August 2016

    Implement “WebAPI” in Asp.NET MVC

    How to implement “WebAPI” in MVC?
    Below are the steps to implement "webAPI" :-Step1:-Create the project using the "WebAPI" template.


    Difference between WCF and WEB API


    With WCF also you can implement REST,So why "WebAPI"?
    WCF was brought in to implement SOA, never the intention was to implement REST."WebAPI'" is built
    from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for
    creating “REST” service “WebAPI” is more preferred.

    Saturday, 13 August 2016

    Convert Amount In Words By JavaScript

    <script>
        //main funtion //
        document.getElementById("tdinword").innerHTML
        = convertNumberToWords(10000000.75);  // Pass your amount
        function convertNumberToWords(amount) {
            var words = new Array();
            words[0] = '';
            words[1] = 'One';
            words[2] = 'Two';
            words[3] = 'Three';
            words[4] = 'Four';
            words[5] = 'Five';
            words[6] = 'Six';
            words[7] = 'Seven';
            words[8] = 'Eight';
            words[9] = 'Nine';
            words[10] = 'Ten';
            words[11] = 'Eleven';
            words[12] = 'Twelve';
            words[13] = 'Thirteen';
            words[14] = 'Fourteen';
            words[15] = 'Fifteen';
            words[16] = 'Sixteen';
            words[17] = 'Seventeen';
            words[18] = 'Eighteen';
            words[19] = 'Nineteen';
            words[20] = 'Twenty';
            words[30] = 'Thirty';
            words[40] = 'Forty';
            words[50] = 'Fifty';
            words[60] = 'Sixty';
            words[70] = 'Seventy';
            words[80] = 'Eighty';
            words[90] = 'Ninety';
            amount = amount.toString();
            var atemp = amount.split(".");
            var number = atemp[0].split(",").join("");
            var n_length = number.length;
            var words_string = "";
            if (n_length <= 9) {
                var n_array = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0);
                var received_n_array = new Array();
                for (var i = 0; i < n_length; i++) {
                    received_n_array[i] = number.substr(i, 1);
                }
                for (var i = 9 - n_length, j = 0; i < 9; i++, j++) {
                    n_array[i] = received_n_array[j];
                }
                for (var i = 0, j = 1; i < 9; i++, j++) {
                    if (i == 0 || i == 2 || i == 4 || i == 7) {
                        if (n_array[i] == 1) {
                            n_array[j] = 10 + parseInt(n_array[j]);
                            n_array[i] = 0;
                        }
                    }
                }
                value = "";
                for (var i = 0; i < 9; i++) {
                    if (i == 0 || i == 2 || i == 4 || i == 7) {
                        value = n_array[i] * 10;
                    } else {
                        value = n_array[i];
                    }
                    if (value != 0) {
                        words_string += words[value] + " ";
                    }
                    if ((i == 1 && value != 0) || (i == 0 && value != 0 && n_array[i + 1] == 0)) {
                        words_string += "Crores ";
                    }
                    if ((i == 3 && value != 0) || (i == 2 && value != 0 && n_array[i + 1] == 0)) {
                        words_string += "Lakhs ";
                    }
                    if ((i == 5 && value != 0) || (i == 4 && value != 0 && n_array[i + 1] == 0)) {
                        words_string += "Thousand ";
                    }
                    if (i == 6 && value != 0 && (n_array[i + 1] != 0 && n_array[i + 2] != 0)) {
                        words_string += "Hundred and ";
                    } else if (i == 6 && value != 0) {
                        words_string += "Hundred ";
                    }
                }
                words_string = words_string.split("  ").join(" ");
            }
            return words_string;
        }
    </script>

    Comments system

    Advertising

    Disqus Shortname