I looked everywhere and I can't figure out what the problem is with my asp project.
Basically I get this error
Invalid object name dbo.Enquires.
It's looking for a table which doesn't exist, and I never mention that table anywhere, not sure why it's looking for it.
EnquireController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using System.Net;
using PetePersonalTrainerFinal.Models;
namespace PetePersonalTrainerFinal.Controllers
{
public class EnquireController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
[Authorize(Roles ="Admin, Mod")]
// Enquire
public ActionResult Index(string SearchName)
{
var items = from i in db.Enquiries select i;
if (!String.IsNullOrEmpty(SearchName))
{
items = items.Where(i => i.Name.Contains(SearchName));
}
return View(items);
}
[Authorize(Roles ="Admin, Mod")]
// Details
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enquire enquire = db.Enquiries.Find(id);
if (enquire == null)
{
return HttpNotFound();
}
return View(enquire);
}
// Create
public ActionResult Create()
{
return View();
}
// Post Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create ([Bind(Include ="Id,Name,Address,Suburb,State,Postcode,Email,Phone,Description")] Enquire enquire)
{
if (ModelState.IsValid)
{
db.Enquiries.Add(enquire);
db.SaveChanges();
TempData["message"] = "Your enquiry has been successufully submitted.";
return RedirectToAction("Index", "Home");
}
return View(enquire);
}
// Edit
[Authorize(Roles = "Admin")]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enquire enquire = db.Enquiries.Find(id);
if (enquire == null)
{
return HttpNotFound();
}
return View(enquire);
}
//Post edit
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult Edit([Bind(Include = "Id,Name,Address,Suburb,State,Postcode,Email,Phone,Description")] Enquire enquire)
{
if (ModelState.IsValid)
{
db.Enquiries.Add(enquire);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(enquire);
}
// Delete
[Authorize(Roles = "Admin")]
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Enquire enquire = db.Enquiries.Find(id);
if (enquire == null)
{
return HttpNotFound();
}
return View(enquire);
}
// Post Delete
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Admin")]
public ActionResult DeleteConfirmed(int id)
{
Enquire enquire = db.Enquiries.Find(id);
db.Enquiries.Remove(enquire);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Enquire.cs Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace PetePersonalTrainerFinal.Models
{
public class Enquire
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
[Display(Name = "Name")]
public string Name { get; set; }
[Required(ErrorMessage = "Address is required")]
[Display(Name = "Address")]
public string Address { get; set; }
[Required(ErrorMessage = "Suburb is required")]
[Display(Name = "Suburb")]
public string Suburb { get; set; }
[Required(ErrorMessage = "State is required")]
[Display(Name = "State")]
public string State { get; set; }
[Required(ErrorMessage = "Postcode is required")]
[Display(Name = "Postcode")]
public string Postcode { get; set; }
[Required(ErrorMessage = "Email is required")]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Phone is required")]
[Display(Name = "Phone")]
public string Phone { get; set; }
[Required(ErrorMessage = "Description is required")]
[Display(Name = "Description")]
public string Description { get; set; }
}
}
And that is The Page I get the error on.
#model IEnumerable<PetePersonalTrainerFinal.Models.Enquire>
#{
ViewBag.Title = "Index";
}
<div class="container">
<h2>Index</h2>
#if (User.IsInRole("Admin"))
{
<p>
#Html.ActionLink("Create New", "Create")
</p>
}
#if (User.IsInRole("Admin") || User.IsInRole("Mod"))
{
using (Html.BeginForm())
{
<p>
Name: #Html.TextBox("SearchName")
<input type="submit" value="Search" />
</p>
}
}
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Suburb)
</th>
<th>
#Html.DisplayNameFor(model => model.State)
</th>
<th>
#Html.DisplayNameFor(model => model.Postcode)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.Phone)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.Suburb)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
#Html.DisplayFor(modelItem => item.Postcode)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Phone)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.ActionLink("Update", "Edit", new { id = item.Id}) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
For some reason I keep getting the error and I can't seem to fix it. I don't have much experience with asp.net. Here is the error I get http://pastebin.com/Gmmhn0VX
It keeps looking for dbo.Enquires and that doesn't exist, I also searched the whole project and I can't see anywhere that something refers to dbo.Enquires.
Any help would be appreciated.
Edit: Here is the ApplicationDBContext
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace PetePersonalTrainerFinal.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/? LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public System.Data.Entity.DbSet<PetePersonalTrainerFinal.Models.Price> Prices { get; set; }
public System.Data.Entity.DbSet<PetePersonalTrainerFinal.Models.Enquire> Enquiries { get; set; }
}
}
Decorating Enquire Model class with [Table("Enquiries")] fixed the issue.
Credits to Ajinder Singh.
Related
I just can't understand I tried everything I could so I hope you guys can help me.
Error message :
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1[BookStore1.Models.Book]', but this ViewDataDictionary instance requires a model item of type 'BookStore1.Models.Account'.
That's like an online book-store and I was trying to make an action with which you can display all books in the database and edit them as an admin.
That's my book model:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BookStore1.Models
{
public class Book
{
[Key]
public int Id { get; set; }
[Required]
public string? Name { get; set; }
[Required]
public string? Author { get; set; } = "Unknown";
[Required]
public int Price { get; set; }
[NotMapped]
public IFormFile? Image { set; get; }
}
}
that's my admin controller:
using BookStore1.Data;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using BookStore1.Models;
namespace BookStore1.Controllers
{
[Authorize(Policy = "HasToBeAdmin")]
public class AdminController : Controller
{
private readonly AppDataContext _database;
private readonly IWebHostEnvironment _webHostEnvironment;
public AdminController(AppDataContext database, IWebHostEnvironment webHostEnvironment)
{
_database = database;
_webHostEnvironment = webHostEnvironment;
}
public IActionResult ShowBooks()
{
var books = _database.Books;
return View(books);
}
[HttpGet]
public IActionResult AddBook()
{
return View();
}
public async Task<IActionResult> AddBook(Book book)
{
if (ModelState.IsValid)
{
string wwwRootPath = _webHostEnvironment.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(book.Image.FileName);
string extention = Path.GetExtension(book.Image.FileName);
string path = Path.Combine(wwwRootPath + "/booksImages", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
await book.Image.CopyToAsync(fileStream);
}
_database.Books.Add(book);
_database.SaveChanges();
return RedirectToAction("ShowBooks", "Admin");
}
return View(book);
}
}
}
The view that won't view:
#model IEnumerable<BookStore1.Models.Book>
#{
ViewData["Title"] = "ShowBooks";
}
<h1>ShowBooks</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Author)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
database context:
using Microsoft.EntityFrameworkCore;
using BookStore1.Models;
namespace BookStore1.Data
{
public class AppDataContext: DbContext
{
public AppDataContext(DbContextOptions<AppDataContext> options): base(options)
{
}
public DbSet<Account> Accounts { get; set; }
public DbSet<Book> Books { get; set; }
}
}
If the view you shown above is ShowBooks.You only need to use _database.Books.ToList() as Serge said.
You use #model IEnumerable<BookStore1.Models.Book> in the view,and you pass System.Collections.Generic.List1[BookStore1.Models.Book]` to the view,it's correct.
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1[BookStore1.Models.Book]', but this ViewDataDictionary instance requires a model item of type 'BookStore1.Models.Account'.
For the error,the view will contains #model BookStore1.Models.Account.You need to find the view which contains it,and check the data passed from action.
you have to fix the action, to convert a dbset to a list and add name of the view to the action if name is not "ShowBooks.cshtml"
public IActionResult ShowBooks()
{
var books = _database.Books.ToList();
return View("viewName", books);
}
I am working on a learning project in which I created a view which displays a list of Delisted Books( isActive = false) populated by calling an api.
The view has a list of books + a checkbox in front of each book so that upon clicking the books we want to set active and hit the save button, it returns the books which are selected to the action in controller.
This is the view I am working with :
#model IEnumerable<MvcBooksList.Models.Book>
#{
ViewData["Title"] = "Delisted Books";
}
#if (Model != null)
{
#using (Html.BeginForm("DelistedForm", "Book", FormMethod.Post, new { #id = "myForm" }))
{
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.BookName)
</th>
<th>
#Html.DisplayNameFor(model => model.Author)
</th>
<th>
#Html.DisplayNameFor(model => model.Publisher)
</th>
<th>
Enlist
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.BookName)
#Html.HiddenFor(modelItem => item.BookName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Author)
#Html.HiddenFor(modelItem => item.Author)
</td>
<td>
#Html.DisplayFor(modelItem => item.Publisher)
#Html.HiddenFor(modelItem => item.Publisher)
</td>
<td>
#Html.CheckBoxFor(modelItem => item.IsActive)
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Save" /> <input type = "button" value = "Cancel" onclick = "location.href='#Url.Action("Index", "Home")'" />
}
}
else
{
<h3>No Books currently delisted</h3>
}
This is the model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MvcBooksList.Models
{
public class Book
{
public string BookName { get; set; }
public string Author { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
public string Publisher { get; set; }
public bool IsActive { get; set; }
public double? Price { get; set; }
public int Pages { get; set; }
public string AddedBy { get; set; }
public string ModifiedBy { get; set; }
public DateTime AddedOn { get; set; }
public DateTime LastModifiedOn { get; set; }
}
}
and this is the controller:
[HttpPost]
public async Task<ActionResult> DelistedForm(IEnumerable<Book> fromDelist)
{
foreach (var item in fromDelist)
{
if (item.IsActive == true)
//CALL
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = baseAddressOfBookApi;
var resopnse = await client.GetAsync("Book/EnlistBook?id="+item.BookName.ToString());
if (!resopnse.IsSuccessStatusCode)
{
return View(null);
}
}
}
}
return RedirectToAction("Index","Home");
}
Dont mind the code inside the action.
So when I press the submit button nothing gets passed to the action. The fromDelist collection is showing a count of 0.
So ,what am I doing wrong.
And Is it possible that I can return the names of books that are checked.
BookController ::
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using MvcBooksList.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace MvcBooksList.Controllers
{
public class BookController : Controller
{
readonly Uri baseAddressOfBookApi;
public BookController(IConfiguration configuration)
{
baseAddressOfBookApi = new Uri(configuration.GetSection("ApiAddress:BookAPI").Value);
}
/*
public ActionResult Edit(string name)
{
return View(name); //repalce with the name of view
}
public ActionResult Delete(string name)
{
return View(name); //repalce with the name of view
}
public ActionResult Delist(string name)
{
return View(name); //repalce with the name of view
}
*/
public async Task<ActionResult> ViewDelistedBooks()
{
List<Book> bookdetails = new List<Book>();
using (HttpClient client = new HttpClient())
{
client.BaseAddress = baseAddressOfBookApi;
var response = await client.GetAsync("Book/ViewDelistedBooks");
if (response.IsSuccessStatusCode)
{
var BookResponse = response.Content.ReadAsStringAsync().Result;
bookdetails = JsonConvert.DeserializeObject<List<Book>>(BookResponse);
}
}
return View(bookdetails);
}
public ActionResult Cancel()
{
return View("~/Views/Home/Index.cshtml");
}
[HttpPost]
public async Task<ActionResult> DelistedForm(IEnumerable<Book> fromDelist)
{
foreach (var item in fromDelist)
{
if (item.IsActive == true)
//CALL
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = baseAddressOfBookApi;
var resopnse = await client.GetAsync("Book/EnlistBook?id="+item.BookName.ToString());
if (!resopnse.IsSuccessStatusCode)
{
return View(null);
}
}
}
}
return RedirectToAction("Index","Home");
}
}
}
Try to replace foreach by for
#model List<MvcBooksList.Models.Book>
#for (int i = 0; i < Model.Count(); i+=1)
{
......
<td>
#Html.DisplayFor(model=> model[i].Publisher)
#Html.HiddenFor(model => model[i].Publisher)
</td>
<td>
#Html.CheckBoxFor(model => model[i].IsActive)
</td>
</tr>
.... and so on for all
and replace a table header
<th>
#Html.DisplayNameFor(model => model[0].BookName)
</th>
<th>
#Html.DisplayNameFor(model => model[0].Author)
</th>
I am new to the ASP.NET Identity framework and I am trying to do some things. What I want to do is to edit the user who has already register and then update the user details to the database...
Previously, I use entity framework, and then its generated my controller view and model it self. But I want to update my user details and getting a list of users into a list..
How do I do these stuff? I have seen role methods..but I never understand,
How can I do? without using role..Because, I don't need administrator purposes. Only, I want to update my user details.
Create a dbcontext object "context" and you also need to create a model class "UserEdit" and include those fields in it which you wants to edit.
private ApplicationDbContext context = new ApplicationDbContext();
// To view the List of User
public ActionResult ListUsers ()
{
return View(context.Users.ToList());
}
public ActionResult EditUser(string email)
{
ApplicationUser appUser = new ApplicationUser();
appUser = UserManager.FindByEmail(email);
UserEdit user = new UserEdit();
user.Address = appUser.Address;
user.FirstName = appUser.FirstName;
user.LastName = appUser.LastName;
user.EmailConfirmed = appUser.EmailConfirmed;
user.Mobile = appUser.Mobile;
user.City = appUser.City;
return View(user);
}
[HttpPost]
public async Task<ActionResult> EditUser(UserEdit model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
var manager = new UserManager<ApplicationUser>(store);
var currentUser = manager.FindByEmail(model.Email);
currentUser.FirstName = model.FirstName;
currentUser.LastName = model.LastName;
currentUser.Mobile = model.Mobile;
currentUser.Address = model.Address;
currentUser.City = model.City;
currentUser.EmailConfirmed = model.EmailConfirmed;
await manager.UpdateAsync(currentUser);
var ctx = store.Context;
ctx.SaveChanges();
TempData["msg"] = "Profile Changes Saved !";
return RedirectToAction("ListUser");
}
// for deleting a user
public ActionResult DeleteUser(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = context.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(context.Users.Find(id));
}
public async Task<ActionResult> UserDeleteConfirmed(string id)
{
var user = await UserManager.FindByIdAsync(id);
var result = await UserManager.DeleteAsync(user);
if (result.Succeeded)
{
TempData["UserDeleted"] = "User Successfully Deleted";
return RedirectToAction("ManageEditors");
}
else
{
TempData["UserDeleted"] = "Error Deleting User";
return RedirectToAction("ManageEditors");
}
}
Below is the View for ListUser:
#model IEnumerable<SampleApp.Models.ApplicationUser>
#{
ViewBag.Title = "ListUsers";
}
<div class="row">
<div class="col-md-12">
<div>
<h3>#ViewBag.Message</h3>
</div>
<div>
<h2>ManageEditors</h2>
<table class="table">
<tr>
<th>
S.No.
</th>
<th>
Email
</th>
<th>
EmailConfirmed
</th>
<th>
FirstName
</th>
<th>
LastName
</th>
<th>
Mobile
</th>
<th></th>
</tr>
#{ int sno = 1;
foreach (var item in Model)
{
<tr>
<td>
#(sno++)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.EmailConfirmed)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mobile)
</td>
<td>
#Html.ActionLink("Edit", "EditUser", new { email=item.Email})
#Html.ActionLink("Delete", "DeleteUser", new { id = item.Id })
</td>
</tr>
}
}
</table>
</div>
</div>
</div>
// below is my UserEdit Model
public class UserEdit
{
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Mobile")]
public string Mobile { get; set; }
[Display(Name = "Address")]
public string Address { get; set; }
[Display(Name = "City")]
public string City { get; set; }
public bool EmailConfirmed { get; set; }
}
//below is my IdentityModel.cs class which have ApplicationDbContext class
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace SampleApp.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
//Extra column added to auto generated Table by Code First approach (ASPNETUSERS) by Entity Framework
public string FirstName { get; set; }
public string LastName { get; set; }
public string DOB { get; set; }
public string Sex { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string Mobile { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
Hope this help you :)
There is a class that comes with asp.net identity called UserManager
this class will help with the user information management you can first find a user using either
FindByIdAsync
FindByEmailAsync
FindByUserName
with the user object, you can then update it with new information for the user profile
and then use the method UpdateAsync to update the user information in the database.
when it comes to getting a list of users you can use the IdentityDbContext class to get the list of users from.
Hi there I was looking for a way to select certain fields from the different database tables and output it into one table in the view.This is the code I have so far although it is only able to retrieve information from the patients table. Any help would be greatly appreciated thanks.
model
namespace ChampPMS.Models
{
public class Patient
{
public int PatientID { get; set; }
public string HouseChartNo { get; set; }
public string ClinicChartNo { get; set; }
public string Title { get; set; }
public string FirstName { get; set; }
public DateTime DOB { get; set; }
Dont think this is right.
//Other Table variables
public Admission ExpectedDate { get; set; } ------->from bed
public Beds Bed { get; set; } ------->from admissions
}
public class Beds
{
public int BedID { get; set; }
public int RoomID { get; set; }
public string Bed { get; set; }
}
public class Admission
{
public int AdmissionID { get; set; }
public int PatientID { get; set; }
public DateTime ExpectedDate { get; set; }
public int BedID { get; set; }
public string Phone { get; set; }
}
public PatientDBContext()
: base("PatientsDBContext")//connection string
{
}
public DbSet<Admission> Admission { get; set; }
public DbSet<Beds> Beds { get; set; }
public DbSet<Patient> Patient { get; set; }
}
view
#model IEnumerable<ChampPMS.Models.Patient>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create", null, new { #class = "btn btn-success" })
</p>
<table class="table table-condensed table-striped table-hover table-bordered ">
<tr>
<th>
#Html.DisplayNameFor(model => model.HouseChartNo)
</th>
<th>
#Html.DisplayNameFor(model => model.ClinicChartNo)
</th>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
#Html.DisplayNameFor(model => model.DOB)
</th>
<th>
#Html.DisplayNameFor(model => model.Bed)----->from bed table
</th>
<th>
#Html.DisplayNameFor(model => model.ExpectedDate)----->from admission table
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.HouseChartNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.ClinicChartNo)
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
#Html.DisplayFor(modelItem => item.SurName)
</td>
<td>
#Html.DisplayFor(modelItem => item.DOB)
</td>
<td>
#Html.DisplayNameFor(model => model.Bed)------->from bed table
</td>
<td>
#Html.DisplayNameFor(model => model.ExpectedDate) ----->from admission table
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.PatientID }, new { #class = "btn btn-xs btn-info" }) |
#Html.ActionLink("Details", "Details", new { id = item.PatientID }, new { #class = "btn btn-xs btn-primary" }) |
#Html.ActionLink("Delete", "Delete", new { id = item.PatientID }, new { #class = "btn btn-xs btn-danger" })
</td>
</tr>
}
</table>
Controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using ChampPMS.Models;
namespace ChampPMS.Controllers
{
public class PatientsController : Controller
{
private PatientDBContext db = new PatientDBContext();
// GET: Patients
public ActionResult Index()
{
return View(db.Patient.ToList());
}
// GET: Patients/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Patient patient = db.Patient.Find(id);
if (patient == null)
{
return HttpNotFound();
}
return View(patient);
}
// GET: Patients/Create
public ActionResult Create()
{
return View();
}
// POST: Patients/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PatientID,HouseChartNo,ClinicChartNo,Title,FirstName,SurName,DOB,HouseName,Street,Town,County,Telephone,Mobile,Gender,Occupation,Marital,TaxNumber,GMSnumber,DPSnumber,ReligionID,Status,HashCode")] Patient patient)
{
if (ModelState.IsValid)
{
db.Patient.Add(patient);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(patient);
}
// GET: Patients/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Patient patient = db.Patient.Find(id);
if (patient == null)
{
return HttpNotFound();
}
return View(patient);
}
// POST: Patients/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "PatientID,HouseChartNo,ClinicChartNo,Title,FirstName,SurName,DOB,HouseName,Street,Town,County,Telephone,Mobile,Gender,Occupation,Marital,TaxNumber,GMSnumber,DPSnumber,ReligionID,Status,HashCode")] Patient patient)
{
if (ModelState.IsValid)
{
db.Entry(patient).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(patient);
}
// GET: Patients/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Patient patient = db.Patient.Find(id);
if (patient == null)
{
return HttpNotFound();
}
return View(patient);
}
// POST: Patients/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Patient patient = db.Patient.Find(id);
db.Patient.Remove(patient);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
Rather than return the data directly from the database to the View you should create a View-Model in the controller action.
This ViewModel would contain all of the information that you need to display.
Using a ViewModel ensures that only the data required for the View is returned. It means rendering your View is more simple and you can use data from many different sources in one single ViewModel.
so I'm new to MVC5 and I'm creating a website without the use of a DB context. How do I go about displaying Model info taken from fields into a view? I cannot use a DB context which would've made this a whole lot easier.
Here's my Controller:
using SaasSocialNetwork.Models;
using SSN.Shared.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using log4net;
namespace SaasSocialNetwork.Controllers
{
public class OpportunitiesController : Controller
{
ILog logger = LogManager.GetLogger(typeof(OpportunitiesController));
//
// GET: /Opportunities/
public ActionResult Index(OpportunityModel opportunity)
{
List<OpportunityModel> opportunities = new List<OpportunityModel>();
opportunities.Add(opportunity);
try
{
//multishops = TownBL.getMultishops().ToList();
return View(opportunities);
}
catch(Exception ex)
{
logger.Error(ex);
TempData["Warnning"] = ex.Message;
return View(opportunities);
}
finally
{
logger.Debug("<<Index");
}
//return View();
}
// GET: /Opportunities/Details/5
public ActionResult Details(OpportunityModel opportunity)
{
logger.Debug(">>Details");
try
{
//MultiShops multishop = TownBL.getMultishops().Single(m => m.ID == id);
//logger.InfoFormat("{0} Multi Shop Details", opportunity.Name);
//var list = new List<string> { "test1", "test2", "test3" };
return View("Details", opportunityModel);
}
catch (Exception ex)
{
logger.Error(ex);
return View("Details");
}
finally
{
logger.Debug("<<Details");
}
return View();
}
// GET: /Opportunities/Create
public ActionResult Create()
{
logger.Debug(">>Create(GET)");
try
{
return View("Create");
}
catch (Exception ex)
{
logger.Error(ex);
return View("Index");
}
finally
{
logger.Debug("<<Create");
}
//return View();
}
//
// POST: /Opportunities/Create
[HttpPost]
public ActionResult Create(OpportunityModel opportunity)
{
try
{
// TODO: Add insert logic here
OpportunityModel object1 = new OpportunityModel();
SSN.Shared.Interfaces.Opportunity opp = new Opportunity();
opp.Name = object1.Name;
opp.Description = object1.Description;
opp.ImageUrl = object1.ImageUrl;
opp.GuidID = object1.GuidID;
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Opportunities/Edit/5
//public ActionResult Edit(Guid GuidId)
//{
// logger.Debug(">>Edit(GET)");
// try
// {
// //MultiShops opportunity = TownBL.getMultishops().Single(m => m.ID == id);
// ViewBag.state = new List<SelectListItem>{
// new SelectListItem { Text = "Active", Value = "Active" },
// new SelectListItem { Text = "Suspended", Value ="Suspended"},
// };
// //return View(opportunity);
// }
// catch (Exception ex)
// {
// logger.Error(ex);
// return View();
// }
// finally
// {
// logger.Debug("<<Edit");
// }
//}
//
// POST: /Opportunities/Edit/5
[HttpPost]
public ActionResult Edit(OpportunityModel opportunity)
{
logger.Debug(">>Edit(GET)");
try
{
if (ModelState.IsValid)
{
//TownBL.UpdateMultiShop(multishop);
logger.InfoFormat("Opportunity {0} Updates", opportunity.Name);
}
TempData["Sucess"] = "Opportunity Sucessfully Updated";
return RedirectToAction("Index");
}
catch (Exception ex)
{
logger.Error(ex);
TempData["Warnning"] = "Error Updating Opportunity";
return View();
}
finally
{
logger.Debug("<<Edit(POST)");
}
}
//
// GET: /Opportunities/Delete/5
//public ActionResult Delete(Guid GuidId)
//{
// logger.Debug(">>Delete(GET)");
// try
// {
// //MultiShops opportunity = TownBL.getMultishops().Single(m => m.ID == id);
// TempData["Sucess"] = "Opportunity Sucessfully Deleted";
// //return View(opportunity);
// }
// catch (Exception ex)
// {
// logger.Error(ex);
// TempData["Warnning"] = "Error Deletting Opportunity";
// return View("Index");
// }
// finally
// {
// logger.Debug("<<Delete(GET)");
// }
//}
//
// POST: /Opportunities/Delete/5
[HttpPost]
public ActionResult Delete(OpportunityModel opportunity)
{
logger.Debug(">>Delete(POST)");
try
{
//TownBL.DeleteMultiShop(multishop.ID);
logger.InfoFormat("{0} Opportunity Deleted", opportunity.Name);
return RedirectToAction("Index");
}
catch (Exception ex)
{
logger.Error(ex);
return View();
}
finally
{
logger.Debug("<<Delete(POST)");
}
}
}
}
My Model:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Security;
namespace SaasSocialNetwork.Models
{
public class OpportunityModel
{
public Guid GuidID { get; set; }
[Required(ErrorMessage = "Enter ID")]
[StringLength(50)]
[RegularExpression("^[0-9a-zA-Z ]+$", ErrorMessage = "ID must be alphanumeric")]
public string Id { get; set; }
[Required(ErrorMessage = "Enter Name")]
[StringLength(50)]
[RegularExpression("^[0-9a-zA-Z ]+$", ErrorMessage = "Name must be alphanumeric")]
public string Name { get; set; }
[Required(ErrorMessage = "Enter Network ID")]
[StringLength(50)]
[RegularExpression("^[0-9a-zA-Z ]+$", ErrorMessage = "ID must be alphanumeric")]
public string NetworkId { get; set; }
[Required(ErrorMessage = "Enter Description")]
public string Description { get; set; }
[Required(ErrorMessage = "Enter image URL")]
public string ImageUrl { get; set; }
/// <summary>
/// This is the name of the organization
/// </summary>
[Required(ErrorMessage = "Enter the organization name")]
[StringLength(50)]
[RegularExpression("^[0-9a-zA-Z ]+$", ErrorMessage = "Name must be alphanumeric")]
public string Organization { get; set; }
}
}
And the view I wish to populate:
#model IEnumerable<SaasSocialNetwork.Models.OpportunityModel>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.GuidID)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.NetworkId)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.ImageUrl)
</th>
<th>
#Html.DisplayNameFor(model => model.Organization)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.GuidID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.NetworkId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.ImageUrl)
</td>
<td>
#Html.DisplayFor(modelItem => item.Organization)
</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 })
</td>
</tr>
}
</table>