ASP.NET MVC Relational DB - c#

I have two models
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public string Image { get; set; }
public List<Teacher> Teachers { get; set; }
}
public class Teacher
{
public int TeacherID { get; set; }
public string TeacherName { get; set; }
public string TeacherLname { get; set; }
public int DepartmentID { get; set; }
public string Image { get; set; }
public Department Department { get; set; }
}
and I have a ViewModel
public class ViewModel
{
public List<Teacher> Teachers { get; set; }
public List<Department> Departments { get; set; }
}
I have a view where I'm displaying Departments
SchoolDbContext db = new SchoolDbContext();
public ActionResult Index()
{
ViewModel model = new ViewModel();
// retreive from database
model.Departments = db.Departments.ToList();
return View(model);
}
and on Details I want to display Teachers with a DepartmentID where I have a relation.
I'm trying to use this
public ActionResult Details(int id = 0)
{
ViewModel model = new ViewModel();
model.Departments = db.Departments.ToList();
model.Teachers = db.Teachers.Where(m => m.DepartmentID == m.DepartmentID);
return View(model);
}
but there is a error
Error 1 Cannot implicitly convert type 'System.Linq.IQueryable<_167School.Models.Teacher>' to 'System.Collections.Generic.List<_167School.Models.Teacher>'. An explicit conversion exists (are you missing a cast?) C:\Users\Admin\documents\visual studio 2013\Projects\167School\167School\Controllers\DepartmentsController.cs 33

Try this :
public ActionResult Details(int id = 0)
{
ViewModel model = new ViewModel();
model.Departments = db.Departments.ToList();
model.Teachers = db.Teachers.Where(m => m.DepartmentID == id).ToList();
return View(model);
}
You you have to return the Teacher entity as a list since its defined as a List in your ViewModel class.

Related

The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`

The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[website.Models.main]', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.List1[website.Models.List]'
Here i have joined four tables using EF include method.This error occurs while i'm doing this method.
controller :
public IActionResult Index()
{
var listAll = db.main
.Include(x => x.Person)
.ThenInclude(x => x.Entity)
.ThenInclude(x => x.Country)
.ToList();
return View(listAll);
}
View :-
#model List<website.Models.List>
#{
ViewData["Title"] = "Index";
}
Models :- I don't know what i did wrong here please give me any solutions
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Collections;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace website.Models
{
public class List
{
public mainmain{ get; set; }
public Persons Person { get; set; }
public other other{ get; set; }
public Entities Entity { get; set; }
public Countries Country { get; set; }
public int countryId { get; internal set; }
}
public class main
{
public int id{ get; set; }
public int TypeId { get; set; }
public int? PersonId { get; set; }
}
public class Person
{
public Person()
{
main= new HashSet<main>();
}
public int PersonId { get; set; }
public string FirstNameEn { get; set; }
public string FirstNameAr { get; set; }
public string SecondNameAr { get; set; }
public string HomePhonePart1 { get; set; }
public string HomePhonePart2 { get; set; }
public ICollection<main> main{ get; set; }
}
public class Other
{
public int PersonId { get; set; }
public string FatherReligio { get; set; }
public bool? Fatherless { get; set; }
public DateTime? FatherDeathDate { get; set; }
public bool? Motherless { get; set; }
}
public classEntity
{
public Entity()
{
Persons = new HashSet<Persons>();
}
public int CountryId { get; set; }
public string Name { get; set; }
public string ResponsibleName { get; set; }
public string Address { get; set; }
public string Pobox { get; set; }
public string PhonePart1 { get; set; }
public string PhonePart2 { get; set; }
public ICollection<Persons> Persons { get; set; }
}
public class country
{
public country()
{
Entity = new HashSet<Entities>();
Persons = new HashSet<Persons>();
}
public string NameEn { get; set; }
public string NameFr { get; set; }
public string NameSp { get; set; }
public string NameUr { get; set; }
public virtual ICollection<Entities> Entity { get; set; }
public ICollection<Persons> Persons { get; set; }
}
}
try to parse the items into your own List object
public IActionResult Index()
{
var listAll = db.main
.Include(x => x.Person)
.ThenInclude(x => x.Entity)
.ThenInclude(x => x.Country)
.ToList();
List<website.Models.List> newList = new List<website.Models.List>();
foreach(var item in listAll){
website.Models.List listItem = new website.Models.List();
listItem.countryId = item.countryId;
//add your remaining fields
newList.Add(listItem);
}
return View(newList);
}
The listAll is a list of the main object, you need to use the corresponding type to accpet it in your razor page:
#model List<website.Models.main>
#{
ViewData["Title"] = "Index";
}
PopulateAssignedSpecialtyData(doctor);
PopulateDropDownLists();
ViewData["DepartmentId"] = new SelectList(_context.Departments, "Id", "Name");
ViewData["DoctorTypeId"] = new SelectList(_context.DoctorTypes, "Id", "Name");
ViewData["BloodGroupId"] = new SelectList(_context.BloodGroups, "Id", "Name");
return View(doctor);
}
// POST: Doctors/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
[Bind("ID,FirstName,MiddleName," +
"LastName,CityID,Designation,DepartmentId,DoctorTypeId,Gender,BloodGroupId," +
"HospitalVisitTimeFrom,HospitalVisitTimeTo,HospitalConsultingDuration,OnlineVisitTimeFrom," +
"OnlineVisitTimeTo,onlineConsultingDuration,PresentAssignment," +
"ShortBiography,DoctorEmail,DoctorQualifications,DoctorAchievements,Addresses,DoctorDocuments,DoctorSpecialties,DoctorPositions,DoctorExperiences,DoctorMemberships,")]
Doctor doctor,
string[] selectedOptions,
List<IFormFile> theFiles
)
{
try
{
UpdateDoctorSpecialties(selectedOptions, doctor);
if (ModelState.IsValid)
{
await AddDocumentsAsync(doctor, theFiles);
_context.Add(doctor);
await _context.SaveChangesAsync();
//Create Users when Doctor create in admin login
var userManager = _serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
if (userManager.FindByEmailAsync(doctor.DoctorEmail).Result == null)
{
IdentityUser user = new IdentityUser
{
UserName = doctor.DoctorEmail,
Email = doctor.DoctorEmail
};
IdentityResult result = userManager.CreateAsync(user, "doctor123").Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user, "Doctor").Wait();
}
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
catch (RetryLimitExceededException /* dex */)
{
ModelState.AddModelError("", "Unable to save changes after multiple attempts. Try again, and if the problem persists, see your system administrator.");
}
catch (DbUpdateException)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
//Validation Error so give the user another chance.
PopulateAssignedSpecialtyData(doctor);
//Get the full city object for the Doctor and then populate DDL
doctor.City = await _context.Cities.FindAsync(doctor.CityID);
PopulateDropDownLists(doctor);
return View(doctor);
}
// GET: Doctors/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var doctor = await _context.Doctors
.Include(d => d.City)
.Include(d => d.DoctorDocuments)
.Include(d => d.DoctorSpecialties)
.ThenInclude(d => d.Specialty)
.AsNoTracking()
.SingleOrDefaultAsync(d => d.ID == id);
if (doctor == null)
{
return NotFound();
}
PopulateAssignedSpecialtyData(doctor);
PopulateDropDownLists(doctor);
return View(doctor);
}

MVC - Unable to set field/property on entity

I have 2 tables in my entity framework:
INATIVOS (Employees)
EMPRESAS (Companies)
When registering an employee I select a company in a #Html.DropDownListFor (List).
The registration is ok, the company is saved correctly. However, when trying to edit a registered employee shows the error "Unable to set field/property on entity" in the Companies list.
INATIVO.cs
public partial class INATIVOS
{
public decimal ID { get; set; }
public string COD_EMPRESA { get; set; }
public string CHAPA { get; set; }
public string NOME { get; set; }
public System.DateTime DATA_NASC { get; set; }
public string PLANO { get; set; }
public short LEI { get; set; }
public short APOSENTADO { get; set; }
public short ESTADO_VIDA { get; set; }
public short ISENTO { get; set; }
public Nullable<System.DateTime> INICIO_VIGENCIA { get; set; }
public Nullable<System.DateTime> FIM_VIGENCIA { get; set; }
public string CPF { get; set; }
public string EMAIL { get; set; }
public string ENDERECO { get; set; }
public string NUMERO { get; set; }
public string COMPLEMENTO { get; set; }
public string BAIRRO { get; set; }
public string CIDADE { get; set; }
public string ESTADO { get; set; }
public string CEP { get; set; }
public string TELEFONE { get; set; }
public string CELULAR { get; set; }
public string OBSERVACAO { get; set; }
public List<DEPENDENTES> DEPENDENTES { get; set; }
public List<EMPRESAS> EMPRESAS { get; set; }
public List<PLANOS_MEDICO> PLANOS_MEDICO { get; set; }
}
InativoController.cs
public ActionResult Index(int? id)
{
INATIVOS inaModel = new INATIVOS();
using (Entidades db = new Entidades())
{
if (id != null)
{
inaModel = db.INATIVOS.Where(x => x.ID == id).FirstOrDefault();
}
inaModel.EMPRESAS = db.EMPRESAS.ToList<EMPRESAS>();
inaModel.PLANOS_MEDICO = db.PLANOS_MEDICO.ToList<PLANOS_MEDICO>();
}
return View(inaModel);
}
If these are navigation properties:
public List<DEPENDENTES> DEPENDENTES { get; set; }
public List<EMPRESAS> EMPRESAS { get; set; }
public List<PLANOS_MEDICO> PLANOS_MEDICO { get; set; }
Then (1) they need to be virtual and (2) they need to be something like IList or ICollection:
public virtual ICollection<DEPENDENTES> DEPENDENTES { get; set; }
public virtual ICollection<EMPRESAS> EMPRESAS { get; set; }
public virtual ICollection<PLANOS_MEDICO> PLANOS_MEDICO { get; set; }
Though, as an aside, what you're doing here is very strange:
inaModel.EMPRESAS = db.EMPRESAS.ToList<EMPRESAS>();
inaModel.PLANOS_MEDICO = db.PLANOS_MEDICO.ToList<PLANOS_MEDICO>();
Essentially what you have in the database is, for a given Employee (INATIVOS) there are relationships to specific Companies (EMPRESAS) and specific Medical Plans (PLANOS_MEDICO). But you're ignoring whatever is in that data and replacing it with all companies and all medical plans in the entire database.
So every time you use this controller action to fetch an existing employee record, it's going to look like that employee has every company and every medical plan. Even though that's not what's in the database. I strongly suspect that's not what you want.
UPDATE: Based on comments on this answer, it sounds like those aren't navigation properties. They're not even properties of the model at all. They're just lists of data needed for the view to populate (presumably) <select> elements.
If they're not part of the data model then remove them from the model. Instead, consider using a view model. For example:
public class InativosViewModel
{
public INATIVOS Inativos { get; set; }
public List<EMPRESAS> EMPRESAS { get; set; }
public List<PLANOS_MEDICO> PLANOS_MEDICO { get; set; }
}
Then in the controller return an instance of the view model, which is a composite object of the model and the data needed for the view:
public ActionResult Index(int? id)
{
InativosViewModel result = new InativosViewModel();
using (Entidades db = new Entidades())
{
if (id != null)
{
result.Inativos = db.INATIVOS.Where(x => x.ID == id).FirstOrDefault();
}
result.EMPRESAS = db.EMPRESAS.ToList<EMPRESAS>();
result.PLANOS_MEDICO = db.PLANOS_MEDICO.ToList<PLANOS_MEDICO>();
}
return View(result);
}
And of course change the model binding in the view itself to now expect and use an instance of InativosViewModel. The resulting POST action can still accept an instance of INATIVOS if it needs to, or it can accept an instance of InativosViewModel just as well. That all depends on what the form structure is and what's being posted to that action.
Alternatively, if you want to keep using the INATIVOS model then still remove those lists from it but use something like ViewBag to send them to the view. Something like this:
public ActionResult Index(int? id)
{
INATIVOS inaModel = new INATIVOS();
using (Entidades db = new Entidades())
{
if (id != null)
{
inaModel = db.INATIVOS.Where(x => x.ID == id).FirstOrDefault();
}
ViewBag.Empresas = db.EMPRESAS.ToList<EMPRESAS>();
ViewBag.PlanosMedico = db.PLANOS_MEDICO.ToList<PLANOS_MEDICO>();
}
return View(inaModel);
}
Then in your view you would populate the <select> elements from there:
#Html.DropDownListFor(
model => Model.COD_EMPRESA,
new SelectList(ViewBag.Empresas, "CODIGO", "DESCRICAO"),
htmlAttributes: new { #class = "form-control"
})

Entity Framework do not load related objects

I'm developing the Music Store sample app with ASP.NET MVC, Entity Framework and WCF.
This is a layered application which has a common layer for the entities.
in the AddToCart Action method , the Album object is populates fine but after the Cart save when wcf loads the cart object the associated Album object is Null, may be some serialization issue (I have not idea), in the view #foreach (var item in Model.CartItems) the item.Album.Title becomes null
This is my code:
public static void AddToCart(Album album, string ShoppingCartID)
{
using (MusicStoreEntities db = new MusicStoreEntities())
{
// Get the matching cart and album instances
var cartItem = db.Carts.SingleOrDefault(
c => c.CartId == ShoppingCartID
&& c.AlbumId == album.AlbumId);
if (cartItem == null)
{
// Create a new cart item if no cart item exists
cartItem = new Cart
{
AlbumId = album.AlbumId,
CartId = ShoppingCartID,
Count = 1,
DateCreated = DateTime.Now
};
db.Carts.Add(cartItem);
}
else
{
// If the item does exist in the cart, then add one to the quantity
cartItem.Count++;
}
// Save changes
db.SaveChanges();
}
}
public static List<Cart> GetCartItems(string ShoppingCartID)
{
using (MusicStoreEntities db = new MusicStoreEntities())
{
return db.Carts.Where(cart => cart.CartId == ShoppingCartID).ToList();
}
}
Controller
namespace MusicStore.Web.Controllers
{
public class ShoppingCartController : Controller
{
MusicShoppingCartMgr.Cart serviceref1 = new MusicShoppingCartMgr.Cart();
MusicShoppingCartMgr.iShoppingCart servicemethodref1 = new iShoppingCartClient();
//
// GET: /ShoppingCart/
public ActionResult Index()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up our ViewModel
var viewModel = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(cart.ShoppingCartId),
CartTotal = cart.GetTotal(cart.ShoppingCartId)
};
// Return the view
return View(viewModel);
}
//
// GET: /Store/AddToCart/5
public ActionResult AddToCart(int id)
{
var addedAlbum = servicemethodref1.GetAlbum(id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedAlbum, cart.ShoppingCartId);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
}
}
Model Classes
namespace MusicStore.Core
{
[Serializable]
[DataContract]
public class Cart
{
[Key]
[DataMember]
public int RecordId { get; set; }
[DataMember]
public string CartId { get; set; }
[DataMember]
public int AlbumId { get; set; }
[DataMember]
public int Count { get; set; }
[DataMember]
public System.DateTime DateCreated { get; set; }
[DataMember]
public virtual Album Album { get; set; }
}
}
namespace MusicStore.Core
{
[Serializable]
[DataContract]
//[Bind(Exclude = "AlbumId")]
public class Album
{
[DataMember]
[ScaffoldColumn(false)]
public int AlbumId { get; set; }
[DataMember]
[DisplayName("Genre")]
public int GenreId { get; set; }
[DataMember]
[DisplayName("Artist")]
public int ArtistId { get; set; }
[DataMember]
[Required(ErrorMessage = "An Album Title is required")]
[StringLength(160)]
public string Title { get; set; }
[DataMember]
[Required(ErrorMessage = "Price is required")]
[Range(0.01, 100.00,
ErrorMessage = "Price must be between 0.01 and 100.00")]
public decimal Price { get; set; }
[DataMember]
[DisplayName("Album Art URL")]
[StringLength(1024)]
public string AlbumArtUrl { get; set; }
[DataMember]
public virtual Genre Genre { get; set; }
[DataMember]
public virtual Artist Artist { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
}
}
DB Context
namespace MusicStore.Data
{
public class MusicStoreEntities : DbContext
{
public MusicStoreEntities()
: base("MusicStoreEntities")
{
var ensureDLLIsCopied = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
this.Configuration.ProxyCreationEnabled = false;
Database.SetInitializer<MusicStoreEntities>(new CreateDatabaseIfNotExists<MusicStoreEntities>());
Database.SetInitializer(new CommonDBInitializer());
}
public DbSet<Album> Albums { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Cart> Carts { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
}
}
Question is: why it is the Album object is not loaded inside Cart object, and how to fix it?
Entity Framework does not load related objects by default to help prevent potential performance problems around loading one-to-many or many-to-many relationships into memory.
Looking at the code you have posted, it seems a potential fix would be for you to add .Include("Album") when getting out the cart items in GetCartItems. It would then become
public static List<Cart> GetCartItems(string ShoppingCartID)
{
using (MusicStoreEntities db = new MusicStoreEntities())
{
return db.Carts.Include("Album").Where(cart => cart.CartId == ShoppingCartID).ToList();
}
}
See the Entity Framework docs for some other options around loading related entities

Mvc Drop Down List With Repository

I am trying to get the id selected from a dropdown so that i can set it against my business logic method. I am using a repository pattern and my code is as follows.
However when i run the program, I get an error The insert statement conflicted with the foreign key.
Database Table
public class Item
{
[Key]
public int ItemId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string ItemArtUrl { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Categories { get; set; }
}
Database table
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual IEnumerable<Item> Items { get; set; }
}
ViewModel
public class ItemViewModel
{
[Key]
public int ItemId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string ItemArtUrl { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public IEnumerable<SelectListItem> CategoriesSelectListItem { get; set;}
}
ViewModel
public class CategoryViewModel
{
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Business Logic Layer
public class ItemBusiness : IItemBusiness
{
public void Insert(ItemViewModel item)
{
var itemrepo = new ItemRepository();
Item i = new Item();
i.Title = item.Title;
i.Price = item.Price;
i.ItemArtUrl = item.ItemArtUrl;
i.CategoryId = item.CategoryId;
itemrepo.Insert(i);
}
public List<ItemViewModel> GetAllItems()
{
var itemrepo = new ItemRepository();
var query = (from x in itemrepo.GetAll()
select new ItemViewModel()
{
Title = x.Title,
Price = x.Price,
ItemArtUrl = x.ItemArtUrl,
CategoryId = x.CategoryId
}).ToList();
return query;
}
}
Controller
[HttpGet]
public ActionResult Create()
{
var categoryBusiness = new CategoryBusiness();
ViewBag.items = new SelectList(categoryBusiness.GetAllCategories(), "CategoryId", "Name");
return View();
}
[HttpPost]
public ActionResult Create(ItemViewModel item)
{
var itemBusiness = new ItemBusiness();
itemBusiness.Insert(item);
return View();
}
public ActionResult Index()
{
var itemBusiness = new ItemBusiness();
return View(itemBusiness.GetAllItems());
}
}
I am assuming your Create view is set up to use ItemViewModel since you are returning it in the [HTTPPost] So instead of using ViewBag.Items = dropdownlist, set your ItemViewModel.CategoriesSelectListItem to that list.
You would have to change your Controller to send an 'empty' ItemViewModel except with the CategoriesSelectionListItem
public ActionResult Create()
{
ItemViewModel ivm = new ItemViewModel();
var categoryBusiness = new CategoryBusiness();
ivm.CategoriesSelectionListItem = new SelectList(categoryBusiness.GetAllCategories(), "CategoryId", "Name");
return View(ivm);
}
Then in your view set up the dropdownlist like this and it will return the CategoryId as part of the Model
#Html.DropDownList("CategoryId", Model.CategoriesSelectListItem, htmlAttributes: new { #class = "form-control" })

ASP.net MVC 5 Editing entry in the database from a view model error - The entity type <myViewModel> is not part of the model for the current context

I've got an edit page that is being populated from a ViewModel. This ViewModel takes in items from a couple of models (Participant, Gender, Country):
ViewModel
namespace MVCManageParticipants.Models
{
public class ParticipantDetailsViewModel
{
public int Id { get; set; }
public int SiteId { get; set; }
public int Status { get; set; }
public string Gender { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public string City { get; set; }
public int CountryId { get; set; }
public string Country { get; set; }
public string Postcode { get; set; }
public string Telephone { get; set; }
public string Notes { get; set; }
public IEnumerable<Country> Countries { get; set; }
}
}
The IEnumerable Countries beings back a full list of countries and fills a dropdown list with the data from a database (this is something I'm wanting to extend on with City, Gender, Status but need to get one working first).
Side question: is how I am doing this the accepted way to fill a dropdown list on the View from a database?
The page populates fine on the [HttpGet] and sends back the ViewModel to the view.
[HttpGet] Controller
var model = (from p in _db.Participants
where p.Id == id
select new ParticipantDetailsViewModel
{
Id = p.Id,
SiteId = p.SiteId,
Status = p.Status,
Gender = p.Gender.Name,
Title = p.Title,
Name = p.Name,
City = p.City.Name,
Country = p.Country.PrettyName,
CountryId = p.Country.Id,
Postcode = p.Postcode,
Telephone = p.Telephone,
Notes = p.Notes,
Countries = _db.Countrys.ToList()
}).FirstOrDefault();
[HttpPost] controller
public ActionResult Edit(ParticipantDetailsViewModel viewModel)
{
if (ModelState.IsValid)
{
_db.Entry(viewModel).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", new { id = viewModel.Id });
}
return View(viewModel);
}
Which is giving me an error on the line _db.Entry(viewModel).State = EntityState.Modified;:
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The entity type ParticipantDetailsViewModel is not part of the model for the current context.
Participant Model
public class Participant
{
public int Id { get; set; }
public int SiteId { get; set; }
public int Status { get; set; }
public Gender Gender { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public City City { get; set; }
public Country Country { get; set; }
public string Postcode { get; set; }
public string Telephone { get; set; }
public string Notes { get; set; }
}
I this because I am trying to update the ViewModel rather than the Participant model? Should I be creating a new Participant object and updating with the incoming data that way?
ParticipantDetailsViewModel is not part of the dbcontext you need to get the Participant object from the database with the id and update it with informations from the viewModel :
public ActionResult Edit(ParticipantDetailsViewModel viewModel)
{
if (ModelState.IsValid)
{
var participant = _db.Participants.FirstOrDefault(p => p.Id == viewModel.Id);
//set all properties whith new values
participant.SiteId = viewModel.SiteId
_db.Entry(participant).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", new { id = viewModel.Id });
}
return View(viewModel);
}

Categories