Monday, 30 January 2017

MVC create edit index dropdownlist bootstrap viewbag tempdata && SQL foreign key relationship













//PersonalController.cs

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

namespace WebApplication3.Controllers
{
    public class PersonalController : Controller
    {
        public void my_viewbags(int _department_id, int _asset_id)
        {
            var _department = department_manager.get_all();
            var _asset = asset_manager.get_all();

            ViewBag.department_dropdownlist = new SelectList(_department, "id", "name", _department_id);
            ViewBag.asset_dropdownlist = new SelectList(_asset, "id", "asset1", _asset_id);
        }

        // GET: Personal
        public ActionResult Index()
        {
            var _personal = personal_manager.get_all();
            return View(_personal.OrderBy(x=>x.name));
        }

        // GET: Personal/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Personal/Create
        public ActionResult Create()
        {
            my_viewbags(0,0);

            return View();
        }

        // POST: Personal/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                if (collection["name"] == "")
                {
                    ViewBag.error_message = "please enter name";
                    my_viewbags(0,0);
                    return View();
                }

                if(personal_manager.check_duplicate(collection["name"]))
                {
                    ViewBag.error_message = collection["name"] + " already exists";
                    my_viewbags(0,0);
                    return View();
                }

                var _personal = new personal_dto()
                {
                    id = Convert.ToInt32(collection["id"]),
                    name = collection["name"],
                    deparment_id = Convert.ToInt32(Request.Form["department_dropdownlist"]),
                    asset_id = Convert.ToInt32(Request.Form["asset_dropdownlist"])
                };

                
                personal_manager.add(_personal);

                TempData["index_status"] = collection["name"] + " is created";

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Personal/Edit/5
        public ActionResult Edit(int id=0)
        {
            var _personal = personal_manager.find(id);

            my_viewbags(_personal.deparment_id,_personal.asset_id);

            return View(_personal);
        }

        // POST: Personal/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
                var _personal = personal_manager.find(id);

                if (collection["name"] == "")
                {
                    ViewBag.error_message = "please enter name";
                    my_viewbags(_personal.deparment_id, _personal.asset_id);
                    return View();
                }

                //name changed but coincide with another existing name
                if (collection["name"] != _personal.name && personal_manager.check_duplicate(collection["name"]))
                {
                    ViewBag.error_message = collection["name"] + " already exists";
                    my_viewbags(_personal.deparment_id, _personal.asset_id);
                    return View();
                }

                var new_personal = new personal_dto()
                {
                    id = Convert.ToInt32(collection["id"]),
                    name = collection["name"],
                    deparment_id = Convert.ToInt32(Request.Form["department_dropdownlist"]),
                    asset_id = Convert.ToInt32(Request.Form["asset_dropdownlist"])
                };

                personal_manager.update(id, new_personal);

                TempData["index_status"] = collection["name"] + " is updated";

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Personal/Delete/5
        public ActionResult Delete(int id)
        {
            var _name = personal_manager.find(id).name;

            personal_manager.delete(id);

            TempData["index_status"] = _name + " is deleted";

            return RedirectToAction("Index");
        }

        // POST: Personal/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}

-----------------------------------------------------------

//~/Views/Index.cshtml

@model IEnumerable<WebApplication3.Models.personal_dto>

@{
    ViewBag.Title = "personal";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table table-striped">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.name)
        </th>

        <th>
            @Html.DisplayNameFor(model => model.deparment_name)
        </th>

        <th>
            @Html.DisplayNameFor(model => model.asset_name)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.name)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.deparment_name)
        </td>

        <td>
            @Html.DisplayFor(modelItem => item.asset_name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.id }) |
            @Html.ActionLink("Details", "Details", new { id=item.id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.id }, new { onclick = "return confirm('Are you sure you wish to delete?');" })
        </td>
    </tr>
}


</table>

<div class="form-group">
    <div>
        @if (TempData["index_status"] != null)
        {
            @Html.Label("status:", htmlAttributes: new { @class = "text-left text-index-status col-md-1" })

            @Html.Label("status", (string)TempData["index_status"], htmlAttributes: new { @class = "text-left text-index-status col-md-11" })
        }
    </div>
</div>

-------------------------------------------------------------------------

//~/Views/Create.cshtml

@model WebApplication3.Models.personal_dto

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>personal_dto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.deparment_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("department_dropdownlist", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.deparment_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.asset_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("asset_dropdownlist", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.asset_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div>
                @if (ViewBag.error_message != null)
                {
                    @Html.Label("error:", htmlAttributes: new { @class = "text-right text-danger col-md-2" })

                    @Html.Label("error", (string)ViewBag.error_message, htmlAttributes: new { @class = "text-left text-danger col-md-10" })
                }
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

-------------------------------------------------------

//~/Views/Edit.cshtml

@model WebApplication3.Models.personal_dto

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>personal_dto</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.id)

        <div class="form-group">
            @Html.LabelFor(model => model.name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.deparment_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("department_dropdownlist", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.deparment_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.asset_name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("asset_dropdownlist", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.asset_name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div>
                @if (ViewBag.error_message != null)
                {
                    @Html.Label("error:", htmlAttributes: new { @class = "text-right text-danger col-md-2" })

                    @Html.Label("error", (string)ViewBag.error_message, htmlAttributes: new { @class = "text-left text-danger col-md-10" })
                }
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

------------------------------------------------------------------------------

//~/App_Start/BundleConfig.cs

using System.Web;
using System.Web.Optimization;

namespace WebApplication3
{
    public class BundleConfig
    {
        // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css",
                      "~/Content/Mystyle.css"));
        }
    }
}

---------------------------------------------------------

//~/Content/MyStyle.css

body {
}

.text-index-status{
    color:gold;
    font-weight: bold;
    font-size: 18px;
}


-----------------------------------------------------------------------

//~/Models/personal_manager.cs

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

namespace WebApplication3.Models
{
    public class personal_manager
    {
        public static testEntities3 db = new testEntities3();

        public static List<personal_dto> get_all()
        {
            var _personal = db.personals.Select(x => new personal_dto
            {
                id = x.id,
                name = x.name,
                asset_name = db.assets.FirstOrDefault(y => y.id == x.asset_id).asset1,
                deparment_name = db.departments.FirstOrDefault(z => z.id == x.deparment_id).name
            }).ToList();

            return _personal;
        }

        public static void add(personal_dto _personal)
        {
            var new_personal = new personal
            {
                id = _personal.id,
                name = _personal.name,
                asset_id = _personal.asset_id,
                deparment_id = _personal.deparment_id
            };

            db.personals.Add(new_personal);

            db.SaveChanges();
        }

        public static void delete(int _id)
        {
            var _personal = db.personals.Find(_id);
            db.personals.Remove(_personal);
            db.SaveChanges();
        }

        public static bool check_duplicate(string _name)
        {
            var _personal = db.personals.FirstOrDefault(x => x.name == _name);

            if(_personal==null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static personal_dto find(int _id)
        {
            var _personal = db.personals.Find(_id);

            var _personal_dto = new personal_dto()
            {
                id = _personal.id,
                name = _personal.name,
                deparment_id = Convert.ToInt32( _personal.deparment_id),
                asset_id = Convert.ToInt32(_personal.asset_id)
            };

            return _personal_dto;
        }

        public static void update(int _id, personal_dto _personal)
        {
            var new_personal = db.personals.Find(_id);

            new_personal.name = _personal.name;
            new_personal.deparment_id = _personal.deparment_id;
            new_personal.asset_id = _personal.asset_id;

            db.SaveChanges();
        }
    }

    public class personal_dto
    {
        public int id { get; set; }
        public string name { get; set; }
        public int deparment_id { get; set; }
        public string deparment_name { get; set; }
        public int asset_id { get; set; }
        public string asset_name { get; set; }
    }
}

--------------------------------------------------------------

//~/Models/department_manager.cs

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

namespace WebApplication3.Models
{
    public class department_manager
    {
        public static List<department_dto> get_all()
        {
            var _department = personal_manager.db.departments.Select(x => new department_dto
            {
                id=x.id,
                name=x.name
            }).ToList();

            return _department;
        }

        public static int find(int _id)
        {
            var department_id = personal_manager.db.personals.FirstOrDefault(x => x.id == _id).deparment_id;

            return Convert.ToInt32( department_id);
        }
    }

    public class department_dto
    {
        public int id { get; set; }
        public string name { get; set; }
    }
}





Reference:

http://www.itorian.com/2013/05/three-ways-to-populate-selected-value.html
http://stackoverflow.com/questions/22991387/how-to-set-default-value-for-asp-net-mvc-dropdownlist-from-model
http://stackoverflow.com/questions/27901175/how-to-get-dropdownlist-selectedvalue-in-controller-in-mvc
http://stackoverflow.com/questions/11103288/html-label-color-in-asp-net-mvc
http://stackoverflow.com/questions/7190682/add-html-textbox-value-from-viewbag
http://stackoverflow.com/questions/16083794/how-to-add-new-css-class-in-html-textbox-mvc4
https://msdn.microsoft.com/en-us/library/bb398783(v=vs.110).aspx
http://stackoverflow.com/questions/14892030/how-to-change-defult-css-file-which-is-apply-to-the-layout-cshtml-using-code-in
http://www.w3schools.com/bootstrap/bootstrap_tables.asp

No comments:

Post a Comment