I have made an earlier post with similar code, and have updated the models to use a helper class instead of a ViewBag. It seemed to work like a charm until the database was updated.
These are my model classes.
[Table("Store")]
public class Store
{
[Key]
public int StoreId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
[Table("Purchase")]
public class Purchase
{
[Key]
public int Id { get; set; }
public int StoreId { get; set; }
[ForeignKey("StoreId")]
public Store Store { get; set; }
}
public class PurchaseDBContext : DbContext
{
public DbSet<Purchase> Purchases { get; set; }
public DbSet<Store> Stores { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
public class PurchaseCreateHelper
{
public Purchase Purchase { get; set; }
public List<Store> Stores { get; set; }
}
}
My relevant part of the View for this question:
<div class="form-group">
#Html.LabelFor(model => model.Purchase.StoreId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Purchase.StoreId, new SelectList(Model.Stores.Select( x => new { StoreId = x.StoreId, DisplayName = x.Name.ToString() + " - " + x.Address.ToString()}), "StoreId", "DisplayName"), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Purchase.StoreId, "", new { #class = "text-danger" })
</div>
</div>
And the relevant part of my controller:
// GET: Purchases/Create
public ActionResult Create()
{
var purchaseHelper = new PurchaseCreateHelper()
{
Stores = db.Stores.ToList(),
Purchase = new Purchase()
};
return View(purchaseHelper);
}
// POST: Purchases/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Purchase purchase)
{
if (ModelState.IsValid)
{
db.Purchases.Add(purchase);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(purchase);
}
When my code comes to db.Purchases.Add(purchase) the Store property of the purchase object is set to null. The StoreId however seems to be perfectly fine. I don't get why the Store object won't change with the StoreId property as I have annotated it with [ForeignKey("StoreId")]. Where did I mess up the connection between StoreId and Store?
UPDATE #2
// GET: Purchases
public ActionResult Index()
{
return View(db.Purchases.ToList());
}
#model IEnumerable<BookKeeper.Models.Purchase>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Store.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Type)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => (item.Store.Name))
</td>
<td>
#Html.DisplayFor(modelItem => item.Type)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</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>
UPDATE #3
enter image description here
I assume that you don't see any value for the purchase.Store, that's because the model binder only bind the StoreId (when request is sent from Browser to Web Server) which you specified in
#Html.DropDownListFor(model => model.Purchase.StoreId, new SelectList(Model.Stores.Select( x => new { StoreId = x.StoreId, DisplayName = x.Name.ToString() + " - " + x.Address.ToString()}), "StoreId", "DisplayName"), new { #class = "form-control" })
The populating of purchase.Store belongs to EF. EF will load that Store when you do
dbContext.Purchases.Include(x => x.Store).FirstOrDefault(x => x.ID == 1234);
UPDATE:
If you want the Store object in POST action
// POST: Purchases/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Purchase purchase)
{
if (ModelState.IsValid)
{
db.Purchases.Add(purchase);
db.SaveChanges();
purchase = dbContext.Purchases.Include(x => x.Store).FirstOrDefault(x => x.ID == purchase.ID); // Not sure why you need Store information at this step.
return RedirectToAction("Index");
}
return View(purchase);
}
Related
As the question says, I am trying to check for a user object's roles in MVC5 View. Basically what my view does is a listing of all the registered users and their current role.
Here's my view:
#model IEnumerable<IconicMx.CandidateDatabase.Models.ApplicationUser>
#{
ViewBag.Title = "Talent Center Institute: Usuarios";
ViewBag.Menu = "Usuarios";
ViewBag.Submenu = "Lista de usuarios";
ViewBag.MenuFaClass = "fa-cog";
ViewBag.InitialPanel = true;
}
<h2>Lista de usuarios</h2>
<p>
#Html.ActionLink("Crear usuario", "Register", "Account", null, new { #class = "btn btn-primary" })
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.name)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
Tipo de usuario
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#if (ViewBag.manager.IsInRole(item.Id, "Admin"))
{
<text>Administrador</text>
}
else
{
<text>Capturista</text>
}
</td>
<td>
#Html.ActionLink("Editar", "Edit", new { id=item.Id }, new { #class = "btn btn-primary btn-xs" }) |
#Html.ActionLink("Eliminar", "Delete", new { id=item.Id }, new { #class = "btn btn-primary btn-xs" })
</td>
</tr>
}
</table>
And here's my controller:
public ActionResult Index()
{
ViewBag.manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
return View(db.Users.ToList());
}
I am trying to use the UserManager's IsInRole function but a runtime error appears when rendering the view saying that function is not defined!! If I invoke this function in the controller it runs as expected.
NOTE: I am NOT trying to get the current logged in User in the session!! (User.identity.IsInRole doesn't help)
First of all, get your data out of database in controller and pass data into your view, not references to service classes. This will save you a lot of headaches. ViewBag is good for passing an odd serialiseable object, but not so good in passing references to classes that have a lot of behaviour.
Second, you need to use IsInRoleAsync method on UserManager. Yes, there is IsInRole non-async extension method available, but I don't see you having a required namespace used.
So I'd do a view model class:
public class UserViewModel
{
public String Id { get; set; }
public String Username { get; set; }
public String Email { get; set; }
public bool IsAdmin { get; set; }
// other properties
}
Then adjust your controller to do the data extraction:
private UserManager<ApplicationUser> userManager;
public MyController()
{
userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());
}
public async Task<ActionResult> Index()
{
var viewModels = db.Users.Select(u => new UserViewModel(){ Id = u.Id, Username = u.Username, Email = u.Email }).ToList();
foreach (var userModel in viewModels)
{
userModel.IsAdmin = await userManager.IsInRoleAsync(userModel.Id, "Admin");
}
return View(viewModels);
}
Then adjust your view to take a List<UserViewModel> and present the data accordingly - I'll leave that to you to finish.
I have two models "Computer" and "Computer Detail." From the Computer's Index page the user can click "View Details" for a given record which redirects to the Index of the Computer Detail and fetches all the records associated with that given "Computer ID" using the query string - That works fine
My problem is I want to have a "Create" link that carries this "Computer ID" (shown in view) and populates the Computer ID field on the Create form.
I used Model.First().ComputerID that worked to run the code with some test records but of course it doesn't work if records for the ComputerID is null.
View
#modelIEnumerable<MyApp.Models.ComputerDetail>
#{
ViewBag.Title = "Index";
}
<h2 class ="page-header">Computer Details</h2>
<div class ="col-lg-12">
<p>
#Html.ActionLink("Create New", "Create", "ComputerDetail", new {id = Model.First().ComputerID}, new { #class = "btn btn-default"})
</p>
<div class="panel panel-default">
<div class ="panel-body">
<table class ="table table-striped" id="dtaTable">
<thead class ="dataTableHead">
<tr>
<th>
#Html.DisplayNameFor(model => model.ComputerID)
</th>
<th>
#Html.DisplayNameFor(model => model.EmployeeID)
</th>
<th>
#Html.DisplayNameFor(model => model.StartDate)
</th>
<th>
#Html.DisplayNameFor(model => model.EndDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Comments)
</th>
<th>Actions</th>
</tr>
</thead>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ComputerID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Employee.FullName)
</td>
<td>
#Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comments)
</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>
</div>
</div>
</div>
Controller
public ActionResult Index(int id)
{
var _FindComputerID = GetComputerDetails(id);
return View(_FindComputerID);
}
private List<ComputerDetail>GetComputerDetails(int id)
{
var FindComputerID = db.ComputerDetails.Where(cd => cd.ComputerID == id).Include
(cd => cd.Employee).OrderByDescending(cd => cd.ID);
return FindComputerID.ToList();
}
[HttpGet]
public ActionResult Create(int id)
{
ComputerDetail computerdetail = new ComputerDetail ();
computerdetail.ComputerID = id;
return View(computerdetail);
}
Model
public class ComputerDetail
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required(ErrorMessage = "Please enter service tag")]
[Display(Name = "Service Tag")]
public int ComputerID { get; set; }
[Required(ErrorMessage = "Please select employee name")]
[Display(Name = "Employee Name")]
public int EmployeeID { get; set; }
[Required(ErrorMessage = "Please enter date")]
[Display(Name = "Date Bought")]
[DataType(DataType.Date)]
public DateTime StartDate { get; set; }
[Display(Name = "Date Bought")]
[DataType(DataType.Date)]
public DateTime? EndDate { get; set; }
public string Comments { get; set; }
//references
public virtual Assets.Computer Computer { get; set; }
public virtual Employee Employee { get; set; }
}
Two thing are happening here:
In the first place, if your view needs to get the ComputerID you may want to reflect this field in the ViewModel and not magically get it from the first item in the list.
public class ComputerDetailsViewModel
{
public int ComputerID {get; set;} // populate in the action directly
public IEnumerable<MyApp.Models.ComputerDetail> Items {get; set;}
}
You really want to go that route, you should use the nullable operator for better error handling figure it out what happens when the ComputerID is null.
#Html.ActionLink("Create New", "Create", "ComputerDetail", new {id = Model.FirstOrDefault()?.ComputerID ?? 0 /*Null case*/}, new { #class = "btn btn-default"})
Hope this help!
I tried this in VS 2015 .net MVC Application and it works perfectly without any trouble.
Instead, trying to test the same with DOTNET CORE 1.x, I can't get the 2^ level navigation property . You've got a situation like that or you know how solve?
DATABASE CLASS
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public Person Person { get; set; }
public Blog Blog { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string Username { get; set; } // I need to show this in the partial view
public string Action { get; set; }
}
CONTROLLER
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
Blog blog = await _context.Blogs
.Include(b=>b.Posts)
.Include(b=>b.Posts.Select(x=>x.Person))
.FirstOrDefaultAsync(b => b.BlogId == id);
//Then.Include don't show property!
if (blog == null)
{
return NotFound();
}
return View(blog);
}
VIEW
#model MyProj.Models.Blog
#{
ViewBag.Title = "Details";
}
<h2>Details</h2>
<div>
<h4>Blog</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.Url)
</dt>
<dd>
#Html.DisplayFor(model => model.Url)
</dd>
</dl>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { id = Model.BlogId }) |
#Html.ActionLink("Back to List", "Index")
</p>
<br />
<div>
#Html.Partial("_posts", this.Model.Posts)
</div>
PARTIAL VIEW
#model IEnumerable<MyProj.Models.Post>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
#Html.DisplayNameFor(model => model.Content)
</th>
<th>
Person
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Content)
</td>
<td>
#Html.DisplayFor(modelItem => item.Person.Username)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.PostId }) |
#Html.ActionLink("Details", "Details", new { id=item.PostId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.PostId })
</td>
</tr>
}
</table>
In my case I cannot get the property Person.Username in a partial that show post list. ThenIclude (with intellisense) don't show the table
Error code :
InvalidOperationException: The property expression 'b => {from Post x in [b].Posts select [x].Person}' is not valid. The expression should represent a property access: 't => t.MyProperty'. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.
Thanks in advance for troubleshooting, I can't figure it out.
I tried to solve this for about 20 hours to understand why it doesn't work..... At end it was egg of Columbus. Thanks to Ivan Stoev for the comment.
Though intellisense doesn't show the related entities, when the app is builded it works.
Blog blog = await _context.Blogs
.Include(b=>b.Posts)
.ThenInclude(p=>p.Person)
.FirstOrDefaultAsync(b => b.BlogId == id);
I have two tables. First is Development region and second is Zone. Zone has got RegionID as a foreign key. I would like to populate all the row from Zone table that is related with the Region selected from the dropdown list. I cannot figure out why the value is not being passed in url string. Please help me out and suggest the best way to accomplish it. Below are the models, controllers and view.
Model Zone
public class Zone
{
[Key]
public int ZoneID { get; set; }
[Required]
[Display(Name = "Zone Code")]
[RegularExpression(#"^[a-zA-Z]*$"), StringLength(5, ErrorMessage = "Code cannot be more than 5 charachter long")]
[Column("ZCode")]
public string ZoneCode { get; set; }
[Display(Name ="Zone"),RegularExpression(#"^[A-Z]+[a-z]*$"),Required]
public string ZoneName { get; set; }
public int RegionID { get; set; }
public virtual DevRegion devregion { get; set; }
[Required]
[Display(Name ="Active")]
public Boolean isActive { get; set; }
}
Model DevRegions
public class DevRegion
{
[Key]
public int RegionID { get; set; }
[Required]
[Display(Name = "Code")]
[RegularExpression(#"^[a-zA-Z]*$"), StringLength(5, ErrorMessage = "Code cannot be more than 5 charachter long")]
[Column("RCode")]
public string RegionCode { get; set; }
[Required]
[Display(Name ="Region")]
[Column("RName")]
[RegularExpression(#"^[A-Z]+[a-zA-Z\s-]*$", ErrorMessage ="Region can only consist of alphabets, space and dash")]
[StringLength(30,ErrorMessage ="Region cannot exceed 30 characters")]
public string RegionName { get; set; }
[Required]
[Display(Name ="Active")]
public Boolean isActive { get; set; }
}
ZonesController
public class ZonesController : Controller
{
private HuRISContext db = new HuRISContext();
// GET: Zones
public ActionResult Index(int? id)
{
ViewBag.RegionID = new SelectList(db.DevRegions, "RegionID", "RegionName");
var zones = db.Zones.Include(z => z.devregion).Where(x=>x.RegionID==(int)(id??x.RegionID));
return View(zones.ToList());
}
Index.cshtml
#model IEnumerable<HuRIS.Models.Zone>
....
<p>#Html.ActionLink("Create New", "Create")</p>
#using (Html.BeginForm("Index","Zones",FormMethod.Get))
{
#Html.AntiForgeryToken();
<div class="panel panel-info">
<div class="panel-body">
<div class="form-group center-block">
<label for="RegionID" class="control-label">Region:</label>
#Html.DropDownList("RegionID", null, "Show all Zones", htmlAttributes: new { #class = "form-control", #onchange = "this.form.submit();" })
</div>
</div>
</div>
}
<table class="table">
<tr>
<th>#Html.DisplayNameFor(model => model.devregion.RegionName)</th>
<th>#Html.DisplayNameFor(model => model.ZoneCode)</th>
<th>#Html.DisplayNameFor(model => model.ZoneName)</th>
<th>#Html.DisplayNameFor(model => model.isActive)</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.devregion.RegionName</td>
<td>#Html.DisplayFor(modelItem => item.ZoneCode)</td>
<td>#Html.DisplayFor(modelItem => item.ZoneName)</td>
<td>#Html.DisplayFor(modelItem => item.isActive)</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ZoneID }) |
#Html.ActionLink("Details", "Details", new { id = item.ZoneID }) | #Html.ActionLink("Delete", "Delete", new { id = item.ZoneID })
</td>
</tr>
}
</table>
JQuery
$(document).ready(function () {
$(".form-control").change(function () {
$.ajax({
url: "~/ZonesController/Index",
type: 'GET',
cache: false,
data: { RegionID: $(".form-control").val() },
success: function (data) {
}
});
});
});
index method as shown below
public ActionResult Index()
{
ViewBag.Region = new SelectList(db.DevRegions, "RegionID", "RegionName");
var allzones = db.Zones.Include(z => z.devregion);
return View(allzones.ToList());
}
create new method as Shown below to accept the id selected on dropdown change event and create the partial view to load on the list of data from the table depending on what is selected on the dropdown:
public ActionResult ZoneList(int? id)
{
var zones = db.Zones.Include(z => z.devregion).Where(x => x.RegionID == (int)(id ?? x.RegionID));
return PartialView("~/Views/PartialViews/_ZoneList.cshtml", zones.ToList());
}
changed javascript as follows.
$("#Region").change(function () {
var selectedID = $(this).val();
$.get('/Zones/ZoneList/' + selectedID, function (data) {
$('.table').html(data);
//$('.table').fadeOut("linear");
//$('.table').fadeIn("linear");
});
});
});
on the index.cshtml changed the code as follows:
#model IEnumerable<HuRIS.Models.Zone>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken();
<div class="panel panel-info">
<div class="panel-body">
<div class="form-group center-block">
<label for="RegionID" class="control-label">Region:</label>
#Html.DropDownList("Region", null, "Show all Zones", htmlAttributes: new { #class = "form-control"})
</div>
</div>
</div>
}
#{
Html.RenderPartial("~/Views/PartialViews/_ZoneList.cshtml", Model);
}
partial view _ZoneList.cshtml
#model IEnumerable<HuRIS.Models.Zone>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.devregion.RegionName)
</th>
<th>
#Html.DisplayNameFor(model => model.ZoneCode)
</th>
<th>
#Html.DisplayNameFor(model => model.ZoneName)
</th>
<th>
#Html.DisplayNameFor(model => model.isActive)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.devregion.RegionName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ZoneCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.ZoneName)
</td>
<td>
#Html.DisplayFor(modelItem => item.isActive)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ZoneID }) |
#Html.ActionLink("Details", "Details", new { id = item.ZoneID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ZoneID })
</td>
</tr>
}
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.