Tuesday, 12 June 2018

Crud Operation

Controller 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DemoApp1.Data.Model;
using DemoApp1.Data;
using DemoApp1.Models;
using System.IO;

namespace DemoApp1.Controllers
{
    public class HomeController : Controller
    {
        private readonly DataDbContext _dbContext = new DataDbContext();
        public string[] ValidFileTypes = { "jpeg", "jpg", "png", "gif" };
        public ActionResult Index()
        {
            try
            {
                List<CustomerInfo> CustData = _dbContext.CustomerInfo.ToList();
                return View(CustData);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

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

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CustomerInfo model, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {

                try
                {

                    CustomerInfo AddModel = new CustomerInfo();
                    if (file != null)
                    {
                        var imagetype = file.FileName.Split('.');
                        if (ValidFileTypes.Contains(imagetype[1].ToLower()))
                        {
                            var fileName = Path.GetFileName(file.FileName);
                            var path = Path.Combine(Server.MapPath("~/Img/"), fileName);
                            var filepathToSave = "Img/" + fileName;
                            file.SaveAs(path);

                            AddModel.Photo = filepathToSave;
                            AddModel.FirstName = model.FirstName;
                            AddModel.LastName = model.LastName;
                            AddModel.PhoneNumber = model.PhoneNumber;

                            _dbContext.CustomerInfo.Add(AddModel);
                            _dbContext.SaveChanges();

                            return RedirectToAction("Index");
                        }

                        ViewBag.CreateError = "Please select valid image type. (jpg, png, gif)";
                    }
                    else
                    {
                        ViewBag.CreateError = "Please select image.";
                    }
                }
                catch (Exception e)
                {

                }
            }

            return View();
        }

        public ActionResult Edit(int id)
        {

            try
            {
                if (id != 0)
                {
                    CustomerInfo customerModel = new CustomerInfo();
                    customerModel = _dbContext.CustomerInfo.Find(id);
                    return View(customerModel);
                }
            }
            catch (Exception e)
            {
            }
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Edit(CustomerInfo model, HttpPostedFileBase file)
        {
            if (!ModelState.IsValid) return View(model);

            try
            {

                CustomerInfo UpdateImg = new CustomerInfo();

                string filepathToSave;
                if (file != null)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    if (fileName != null)
                    {
                        var fileNewName = fileName.Split('.');
                        if (ValidFileTypes.Contains(fileNewName[1].ToLower()))
                        {
                            var path = Path.Combine(Server.MapPath("~/Img/"), fileName);
                            if (System.IO.File.Exists(path))
                            {
                                fileName = fileNewName[0] + DateTime.Now.Ticks + "." + fileNewName[1];
                                var pathD = Path.Combine(Server.MapPath("~/Img/"), fileName);
                                filepathToSave = "Img/" + fileName;
                                file.SaveAs(pathD);

                                UpdateImg = _dbContext.CustomerInfo.Find(model.ID);
                                UpdateImg.Photo = filepathToSave;
                                UpdateImg.FirstName = model.FirstName;
                                UpdateImg.LastName = model.LastName;
                                UpdateImg.PhoneNumber = model.PhoneNumber;

                                _dbContext.SaveChanges();

                            }
                            else
                            {
                                filepathToSave = "Img/" + fileName;
                                file.SaveAs(path);

                                UpdateImg = _dbContext.CustomerInfo.Find(model.ID);
                                UpdateImg.Photo = filepathToSave;
                                UpdateImg.FirstName = model.FirstName;
                                UpdateImg.LastName = model.LastName;
                                UpdateImg.PhoneNumber = model.PhoneNumber;

                                _dbContext.SaveChanges();

                            }
                        }
                        else
                        {

                            ViewBag.EditError = "Please select valid image type. (jpg,png,gif)";
                            var imageTypeDetails = _dbContext.CustomerInfo.Where(z => z.ID == model.ID).FirstOrDefault();
                            ViewBag.ImageType = imageTypeDetails;
                            return View(model);
                        }
                    }
                    TempData["CustomerSuccess"] = "Customer info updated successfully.";
                    return RedirectToAction("Index");
                }
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {

            }
            return View(model);
        }
        public ActionResult Delete(int id)
        {
            var Delete = _dbContext.CustomerInfo.Find(id);
            _dbContext.CustomerInfo.Remove(Delete);
            _dbContext.SaveChanges();
            return RedirectToAction("Index");
        }


    }
}


Index View

@model IEnumerable<DemoApp1.Data.Model.CustomerInfo>

@{
    ViewBag.Title = "Home Page";
}
<!--  TITLE START  -->
<div class="grid_9">
    <div>
        <span style="float: left;">
            <h1 class="image">Customer Management</h1>
        </span>
    </div>
</div>
<!--RIGHT TEXT/CALENDAR-->
<div class="grid_6" id="eventbox">
    @*<a href="#" class="inline_calendar">You don't have any events for today! Yay!</a>*@
    <div class="hidden_calendar"></div>
</div>
<!--RIGHT TEXT/CALENDAR END-->
<div class="clear">
</div>
<!--  TITLE END  -->
<!-- #PORTLETS START -->
<br />
<div id="portlets">
    <!--THIS IS A WIDE PORTLET-->
    <div class="portlet">
        <div class="portlet-content nopadding">
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Manage Customer", "Create", "Home")</li>
                </ul>
            </div>

            <table class="table">
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Phone Number</th>
                    <th>Image</th>
                    <td>Edit</td>
                    <td>Delete</td>
                </tr>
                @if (Model != null)
                {
                    foreach (var item in Model)
                    {
                        <tr>
                            <td>@item.FirstName</td>
                            <td>@item.LastName</td>
                            <td>@item.PhoneNumber</td>
                            <td><img src="../@item.Photo" alt="@item.FirstName" width="150px" /></td>
                            <td> @Html.ActionLink("Edit", "Edit", new { id = item.ID })</td>
                            <td>@Html.ActionLink("Delete", "Delete", new { id = item.ID }) </td>
                        </tr>
                    }
                }
            </table>
        </div>
    </div>
</div>
<!--  END #PORTLETS -->



Create View

@model DemoApp1.Data.Model.CustomerInfo

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}


<!--  TITLE START  -->
<div class="grid_9">
    <h1 class="content_edit">Create Customer</h1>
</div>
<!--RIGHT TEXT/CALENDAR-->
<div class="grid_6" id="eventbox">
    @*<a href="#" class="inline_calendar">You don't have any events for today! Yay!</a>*@
    <div class="hidden_calendar"></div>
</div>
<!--RIGHT TEXT/CALENDAR END-->
<div class="clear">
</div>
<!--  TITLE END  -->
<!-- #PORTLETS START -->
<div id="portlets">
    <!--THIS IS A WIDE PORTLET-->
    <div class="portlet">
        @if (ViewBag.CreateError != null)
        {
            <p id="error" class="info">
                <span class="info_inner">@ViewBag.CreateError</span>
            </p>
        }
        <div class="nopadding">
            @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                @Html.AntiForgeryToken()

                <table style="width:100%">
                    <tr>
                        <td>
                            <div class="form_new_title w30per">First Name:</div>
                            <div class="w70per">
                                @Html.TextBoxFor(model => model.FirstName, new { @class = "largeInput form-control input-lg", @maxlength = "50", @style = "width:50%;padding:6px 12px;" })
                                <span style="vertical-align: middle; color: red; font-weight: 400;">  @Html.ValidationMessageFor(model => model.FirstName)</span>
                            </div>
                            <div class="clearfix"></div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div class="form_new_title w30per">Last Name:</div>
                            <div class="w70per">
                                @Html.TextBoxFor(model => model.LastName, new { @class = "largeInput form-control input-lg", @maxlength = "50", @style = "width:50%;padding:6px 12px;" })
                                <span style="vertical-align: middle; color: red; font-weight: 400;">  @Html.ValidationMessageFor(model => model.LastName)</span>
                            </div>
                            <div class="clearfix"></div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div class="form_new_title w30per">Phone Number:</div>
                            <div class="w70per">
                                @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "largeInput form-control input-lg", @maxlength = "50", @style = "width:50%;padding:6px 12px;" })
                                <span style="vertical-align: middle; color: red; font-weight: 400;">  @Html.ValidationMessageFor(model => model.PhoneNumber)</span>
                            </div>
                            <div class="clearfix"></div>
                        </td>
                    </tr>
                    <tr>
                    <tr>
                        <td>
                            <div class="form_new_title w30per">Image:</div>
                            <div class="w70per">
                                <input type="file" onchange="readURL(this);" name="file" class="largeInput form-control input-lg" style="width:50%;padding:6px 12px;" />
                                <img id="ImgAdd" style="border:1px solid #E1E2E3;padding:3px; margin-top:10px; border-radius:5px; max-height:100px; max-width:100px;" alt="" />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div class="w30per"></div>
                            <div class="w70per">
                                <input type="submit" class="Login_submit" value="Save" style="width:100px;margin-right:10px;padding:5px 10px;background:#1ab394;border-radius:0;border:1px solid #1ab394;box-shadow:none;" />
                                <a class="button_grey" style="width:100px;text-align:center;background:#bababa;border-radius:0;border:1px solid #bababa;color:#fff;height:30px;line-height:30px;padding:0px !important;" href="@Url.Content("~/Home/Index")">Cancel</a>
                            </div><div class="clearfix"></div>
                        </td>
                    </tr>
                </table>
            }
        </div>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}


Edit View

@model DemoApp1.Data.Model.CustomerInfo

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
    var imagePath = @Model.Photo;
}


<!--  TITLE START  -->
<div class="grid_9">
    <h1 class="content_edit">Edit Customer Info</h1>
</div>
<!--RIGHT TEXT/CALENDAR-->
<div class="grid_6" id="eventbox">
    @*<a href="#" class="inline_calendar">You don't have any events for today! Yay!</a>*@
    <div class="hidden_calendar"></div>
</div>
<!--RIGHT TEXT/CALENDAR END-->
<div class="clear">
</div>
<!--  TITLE END  -->
<!-- #PORTLETS START -->
<div id="portlets">
    <!--THIS IS A WIDE PORTLET-->
    <div class="portlet">
        @if (ViewBag.EditError != null)
        {
            <p id="error" class="info">
                <span class="info_inner">@ViewBag.EditError</span>
            </p>
        }
        <div class="nopadding">
            @using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                @Html.AntiForgeryToken()
                <table style="width:100%">
                    <tr>
                        <td>
                            <div class="form_new_title w30per">First Name:</div>
                            <div class="w70per">
                                @Html.TextBoxFor(model => model.FirstName, new { @class = "largeInput form-control input-lg", @maxlength = "50", @style = "width:50%;padding:6px 12px;" })
                                <span style="vertical-align: middle; color: red; font-weight: 400;">  @Html.ValidationMessageFor(model => model.FirstName) @Html.HiddenFor(model => model.ID)</span>
                            </div>
                            <div class="clearfix"></div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div class="form_new_title w30per">Last Name:</div>
                            <div class="w70per">
                                @Html.TextBoxFor(model => model.LastName, new { @class = "largeInput form-control input-lg", @maxlength = "50", @style = "width:50%;padding:6px 12px;" })
                                <span style="vertical-align: middle; color: red; font-weight: 400;">  @Html.ValidationMessageFor(model => model.LastName)</span>
                            </div>
                            <div class="clearfix"></div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div class="form_new_title w30per">Phone Number:</div>
                            <div class="w70per">
                                @Html.TextBoxFor(model => model.PhoneNumber, new { @class = "largeInput form-control input-lg", @maxlength = "50", @style = "width:50%;padding:6px 12px;" })
                                <span style="vertical-align: middle; color: red; font-weight: 400;">  @Html.ValidationMessageFor(model => model.PhoneNumber)</span>
                            </div>
                            <div class="clearfix"></div>
                        </td>
                    </tr>
                    <tr>

                        <td>
                            <div class="form_new_title w30per">Image:</div>
                            <div class="w70per">
                                <div> <input type="file" onchange="readURL(this);"  name="file" class="largeInput form-control input-lg" style="width:50%;padding:6px 12px;" /></div>
                                <p style="width: 150px;">
                                    @Html.HiddenFor(model => model.Photo)
                                    <img id="ImgAdd"  src="../../@Url.Content(Model.Photo)" style="border:1px solid #E1E2E3;padding:3px; margin-top:10px; border-radius:5px; max-height:100px; max-width:100px;" />
                                </p>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div class="w30per"></div>
                            <div class="w70per">
                                <input type="submit" class="Login_submit" value="Save" style="width:100px;margin-right:10px;padding:5px 10px;background:#1ab394;border-radius:0;border:1px solid #1ab394;box-shadow:none;" />
                                <a class="button_grey" style="width:100px;text-align:center;background:#bababa;border-radius:0;border:1px solid #bababa;color:#fff;height:30px;line-height:30px;padding:0px !important;" href="@Url.Content("~/Home/Index")">Cancel</a>
                            </div><div class="clearfix"></div>
                        </td>
                    </tr>
                </table>
            }
        </div>
    </div>
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

DBContect Structure if you want without migration

public partial class DataDbContext : DbContext
    {
        static DataDbContext()
        {
            Database.SetInitializer<DataDbContext>(null);
        }

        public DataDbContext() :base("name=DataEntities")
        {
           
        }
        public DbSet<CustomerInfo> CustomerInfo { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
        }

    }

AngularJs6 using with Asp.net Core Web API 2

AngularJs6 using with Asp.net Core Web API 2 Steps 1) Create project using with command 2) Create services 3) Create routing 4) Modif...