Saturday, February 29, 2020

MVC Core ViewBag and Request.Form

ViewBag is a method to pass data from Controller to View.

Request.Form is the method to extract the value of an html control.


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

  [HttpPost]
  public IActionResult Index(string str)
  {
      //ViewBag.Hello = "Hello " + Request.Form["Name"] + " located at " + Request.Form["Location"];
        ViewBag.Hello = $"Hello {Request.Form["Name"]}  located at {Request.Form["Location"]} specializing in {Request.Form["Spec"]}";
            return View();
   }

@ViewBag.Hello

<form method="post" asp-controller="Home" asp-action="Index">
    <div>
        Name 
        <input type="text" name="Name"  />
    </div>
    <div>
        Location
        <input type="text" name="Location"  />
    </div>
    <div>
        Specialization
        <select id="Spec" name="Spec">
            <option value=".Net">.Net</option>
            <option value=".Net Core">.Net Core</option>
        </select>
    </div>
    <input type="submit"/>
</form>

Thursday, February 13, 2020

Entity Framework Core with Asp .Net Core MVC 3 Code Snippets

Entity Framework Core is the Microsoft's cross, open source, light weight platform framework for data access in .Net applications.

EF Core is an ORM (Object Relation Mapper) which generates most of the data access code. EF Core can be used with a wide range of databases.

 Here I am using SQL Server as the back end.I am going to create a Contact Management System comprising of two tables Groups and Contacts.

Tables

CREATE TABLE [dbo].[Groups](

    [GroupId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,

    [GroupName] [varchar](50) NULL)


CREATE TABLE [dbo].[Contacts](

    [ContactId] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,

    [ContactName] [varchar](40) NULL,

    [Location] [varchar](40) NULL,

    [Phone] [varchar](40) NULL,

    [GroupId] [int] NULL REFERENCES Groups(GroupId))




 Start a new ASP.NET CoreWeb Application.

Select Web Application (Model-View-Controller)


Set reference to Microsoft.EntityFrameworkCore.SqlServer


  Models 

Model represents object oriented representation of tables.

 Models/Group.cs

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

namespace EFCoreMVC.Models

{

    public class Group

    {

        [Key]

        public int GroupId { get; set; }

        public string GroupName { get; set; }

        public List<Contacts> { get; set; }
    }
}


Models/Contact.cs

namespace EFCoreMVC.Models

{

    public class Contact

    {

        public int ContactId { get; set; }

        public string ContactName { get; set; }

        public string Location { get; set; }

        public Group Groups { get; set; }

    }

}


Groups/SimplifiedContactManagementContext
using Microsoft.EntityFrameworkCore;


namespace EFCoreMVC.Models

{

    public class SimplifiedContactManagementContext : DbContext

    {

        public DbSet Groups { get; set; }
        public DbSet Contacts { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("Data Source=.;Initial Catalog=SimplifiedContactManagement;Integrated Security=True");
            base.OnConfiguring(optionsBuilder);
        }
    }
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
     services.AddControllersWithViews();
     services.AddScoped ();
}
 

Controllers

GroupsController
using EFCoreMVC.Models;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using System.Linq;

using System.Threading.Tasks;


namespace EFCoreMVC.Controllers

{

    public class GroupsController : Controller

    {

        private readonly SimplifiedContactManagementContext _context;


        public GroupsController(SimplifiedContactManagementContext context)

        {

            _context = context;

        }


        // GET: Groups

        public async Task Index()
        {
            return View(await _context.Groups.ToListAsync());
        }

        // GET: Groups/Details/5
        public async Task Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @group = await _context.Groups
                .FirstOrDefaultAsync(m =&gt; m.GroupId == id);
            if (@group == null)
            {
                return NotFound();
            }

            return View(@group);
        }

        // GET: Groups/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Groups/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Create([Bind("GroupId,GroupName")] Group @group)
        {
            if (ModelState.IsValid)
            {
                _context.Add(@group);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(@group);
        }

        // GET: Groups/Edit/5
        public async Task Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @group = await _context.Groups.FindAsync(id);
            if (@group == null)
            {
                return NotFound();
            }
            return View(@group);
        }

        // POST: Groups/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Edit(int id, [Bind("GroupId,GroupName")] Group @group)
        {
            if (id != @group.GroupId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(@group);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!GroupExists(@group.GroupId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(@group);
        }

        // GET: Groups/Delete/5
        public async Task Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var @group = await _context.Groups
                .FirstOrDefaultAsync(m =&gt; m.GroupId == id);
            if (@group == null)
            {
                return NotFound();
            }

            return View(@group);
        }

        // POST: Groups/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task DeleteConfirmed(int id)
        {
            var @group = await _context.Groups.FindAsync(id);
            _context.Groups.Remove(@group);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool GroupExists(int id)
        {
            return _context.Groups.Any(e =&gt; e.GroupId == id);
        }
    }
}
 
ContactsController
using EFCoreMVC.Models;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using System.Linq;

using System.Threading.Tasks;


namespace EFCoreMVC.Controllers

{

    public class ContactsController : Controller

    {

        private readonly SimplifiedContactManagementContext _context;


        public ContactsController(SimplifiedContactManagementContext context)

        {

            _context = context;

        }


        // GET: Contacts

        public async Task Index()
        {
           
            return View(await _context.Contacts.ToListAsync());
        }

        // GET: Contacts/Details/5
        public async Task Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var contact = await _context.Contacts
                .FirstOrDefaultAsync(m =&gt; m.ContactId == id);
            if (contact == null)
            {
                return NotFound();
            }

            return View(contact);
        }

        // GET: Contacts/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Contacts/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Create([Bind("ContactId,ContactName,Location")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                _context.Add(contact);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(contact);
        }

        // GET: Contacts/Edit/5
        public async Task Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var contact = await _context.Contacts.FindAsync(id);
            if (contact == null)
            {
                return NotFound();
            }
            return View(contact);
        }

        // POST: Contacts/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task Edit(int id, [Bind("ContactId,ContactName,Location")] Contact contact)
        {
            if (id != contact.ContactId)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(contact);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ContactExists(contact.ContactId))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(contact);
        }

        // GET: Contacts/Delete/5
        public async Task Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var contact = await _context.Contacts
                .FirstOrDefaultAsync(m =&gt; m.ContactId == id);
            if (contact == null)
            {
                return NotFound();
            }

            return View(contact);
        }

        // POST: Contacts/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task DeleteConfirmed(int id)
        {
            var contact = await _context.Contacts.FindAsync(id);
            _context.Contacts.Remove(contact);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool ContactExists(int id)
        {
            return _context.Contacts.Any(e =&gt; e.ContactId == id);
        }
    }
}
 



 
Groups Views
 Index  
@model IEnumerable<EFCoreMVC.Models.Group>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.GroupName)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.GroupName)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.GroupId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.GroupId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.GroupId">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

Details
@model EFCoreMVC.Models.Group

@{
    ViewData["Title"] = "Details";
}

<h1>Details</h1>

<div>
    <h4>Group</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.GroupName)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.GroupName)
        </dd>
    </dl>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.GroupId">Edit</a> |
    <a asp-action="Index">Back to List</a>
</div>


Delete
@model EFCoreMVC.Models.Group

@{
    ViewData["Title"] = "Delete";
}

<h1>Delete</h1>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Group</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.GroupName)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.GroupName)
        </dd>
    </dl>
    
    <form asp-action="Delete">
        <input type="hidden" asp-for="GroupId" />
        <input type="submit" value="Delete" class="btn btn-danger" /> |
        <a asp-action="Index">Back to List</a>
    </form>
</div>


Edit


@model EFCoreMVC.Models.Group

@{
    ViewData["Title"] = "Edit";
}

<h4>Group</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="GroupId" />
            <div class="form-group">
                <label asp-for="GroupName" class="control-label"></label>
                <input asp-for="GroupName" class="form-control" />
                <span asp-validation-for="GroupName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Create
@model EFCoreMVC.Models.Group

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Group</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="GroupName" class="control-label"></label>
                <input asp-for="GroupName" class="form-control" />
                <span asp-validation-for="GroupName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


Contacts Views

Index

@model IEnumerable<EFCoreMVC.Models.Contact>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ContactName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Location)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ContactName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Location)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.ContactId">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.ContactId">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.ContactId">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>




Detail
@model EFCoreMVC.Models.Group

@{
    ViewData["Title"] = "Details";
}

<h1>Details</h1>

<div>
    <h4>Group</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.GroupName)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.GroupName)
        </dd>
    </dl>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.GroupId">Edit</a> |
    <a asp-action="Index">Back to List</a>
</div>

Delete
@model EFCoreMVC.Models.Group

@{
    ViewData["Title"] = "Delete";
}

<h1>Delete</h1>

<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Group</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.GroupName)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.GroupName)
        </dd>
    </dl>
    
    <form asp-action="Delete">
        <input type="hidden" asp-for="GroupId" />
        <input type="submit" value="Delete" class="btn btn-danger" /> |
        <a asp-action="Index">Back to List</a>
    </form>
</div>


Edit
@model EFCoreMVC.Models.Group

@{
    ViewData["Title"] = "Edit";
}

<h1>Edit</h1>

<h4>Group</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="GroupId" />
            <div class="form-group">
                <label asp-for="GroupName" class="control-label"></label>
                <input asp-for="GroupName" class="form-control" />
                <span asp-validation-for="GroupName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}


Create
@model EFCoreMVC.Models.Group

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Group</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="GroupName" class="control-label"></label>
                <input asp-for="GroupName" class="form-control" />
                <span asp-validation-for="GroupName" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}