Class Id from view to other class/view MVC 4 - c#

So i'm working with MVC 4 and i have a question. I have two classes, Schedule and Simulation(its to simulate a student to enter the classroom). I have a view that gives all the schedules that exists next to a link to simulate entrance (it's another view, another class). I would like to pass the id from the schedule that the person chooses to a attribute in the Simulation class.
Class simulation:
namespace GestorSalas.Models
{
public class Simulation
{
public virtual int SimulationId { get; set; }
public virtual int ScheduleId { get; set; }
public virtual string Utilizador { get; set; }
[DisplayName("Tipo de Utilizador")]
public virtual string TipoUtilizador { get; set; }
public virtual int Codigo { get; set; }
public virtual string Hora { get; set; }
public virtual bool Entrar { get; set; }
}
Class Schedule:
namespace GestorSalas.Models
{
public class Schedule
{
public virtual int ScheduleId { get; set; }
public virtual int DisciplinaId { get; set; }
public virtual int SalaId { get; set; }
[Required]
public virtual int Dia { get; set; }
[Required]
[DisplayName("Hora de Entrada")]
public virtual string HoraEntrada { get; set; }
[Required]
[DisplayName("Hora de Saida")]
public virtual string HoraSaida { get; set; }
public virtual Disciplina Disciplina { get; set; }
public virtual Sala Sala { get; set; }
}
This is the view: (what the user sees)
(Entrar na sala=link to the simulation create view, in this image is the schedule index view).
I would like to pass the id from the schedule in order to appear in the simulation form (or in the table after the creation, much like when we click details or edit and it takes the user id but i want the schedule id).
This is the code in the "Entrar em sala" link:
#Html.ActionLink("Entrar em sala", "Create", "Simulation", new {id = item.HorarioId }, null)
But it doesn't work. Any ideas on how can i do this?
EDIT: The controllers:
Simulation:
To create
//
// GET: /Simulacao/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Simulacao/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Simulation simulation)
{
if (ModelState.IsValid)
{
db.Simulacaos.Add(simulation);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(simulation);
}
And the schedule is just the index that is being used here:
public ActionResult Index()
{
var schedules= db.Schedules.Include(h => h.Disciplina).Include(h => h.Sala);
return View(schedules.ToList());
}

Your create method should accept the id as a parameter and use it as needed.
public ActionResult Create(int id)
{
// Id has the scheduleId
// to do : Do something with the Id passed in and return something
}
and in your index view, you need to pass the scheduleId as value of route param Id
#model List<Schedule>
<h2>Simulator</h2>
<table>
<tr><th>HoraEntrada </th><th>Dia </th><th></th></tr>
#foreach(var item in Model)
{
<tr>
<td>#item.HoraSaida</td>
<td>#item.Dia</td>
<td>#Html.ActionLink("Entrar em sala", "Create", "Simulation",
new {#id = item.ScheduleId}, null)
</td>
</tr>
}
</table>

Related

Having trouble with Entity Framework and relationships

I'm having difficulty understanding how to create relationships with the entity framework. (I'm using the MVC architecture, and code first migrations )for example, if I have a class
public class Employee
{
public int Id { get; set; }
public string PIN { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
and I have another class, let's say for example I wish to track employees hours
public class EmployeeHours
{
public int Id { get; set; }
public DateTime? ClockIn { get; set; }
public DateTime? ClockOut { get; set; }
public Employee emplyee { get; set; }
}
I'm having a difficult time understanding how I can have these two classes to interact with each other. Like if John Smith's PIN is 1234, and he enters his PIN into a textbox, how do I successfully add his clock in time and date to the employee hours class?
and if I have a view that looks like this for the employee to enter their PIN
#using (Html.BeginForm("ClockIn", "Login"))
{
#Html.LabelFor(c => c.Employee.PIN)
#Html.TextBoxFor(c => c.Employee.PIN)<br />
<button type="submit">Save</button>
}
and the clockIn controller looks like this
[HttpPost]
public ActionResult ClockIn(string Pin)//employee clocking in
{
_context.EmployeeHours.Add();
_context.SaveChanges();
return View();
}
I'm trying to figure out how to store the time and date associated with this employee in the class, so I can go back and see when this employee clocked in. Thanks!
Add a Navigation Property to Employee, EG:
public class Employee
{
public int Id { get; set; }
public string PIN { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<EmployeeHours> Hours { get; } = new HashSet<EmployeeHours>();
}
Then use it something like this:
[HttpPost]
public ActionResult ClockIn(string pin)//employee clocking in
{
var emp = _context.Employees.Where(e => e.Pin == pin).First();
var hours = new EmployeeHours();
hours.StartTime = DateTime.Now;
//...
emp.Hours.Add(hours);
_context.SaveChanges();
return View();
}

MVC get child count in Index view

I used scaffolding to create the Index, Details, Create, Edit and Delete views and the controller. I have two view models (Parent / Child) relation. In my Index view I want to display the list of Teams as well as some information on the players (Parent / child). For example I want to display in the Index view the teams with the players count per team and last players that was modified. I am not sure where to begin.
Example:
(Team) Red -- (Last Modified) 01/02/2015 -- (Number Players) 10 and so on.
Team ViewModel
public class TeamVM
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime? LastActivity { get; set; }
public string NumberPlayers { get; set; }
public IList<PLayerVM> PlayerVM { get; set; }
}
Player ViewModel
public class PlayerVM
{
public int ID { get; set; }
public int TeamID { get; set; }
public string PlayerInfo { get; set; }
public DateTime? CreateDate { get; set; }
}
Other ViewModel
public class TeamViewModel
{
public List<Team> Teams{ get; set; }
}
Controller
public ActionResult Index()
{
TeamViewModelviewModel = new TeamViewModel();
viewModel.Teams= db.Teams.ToList();
return View(viewModel);
}
db.Products.ToList()?? I assume that is where you mean db.Teams.ToList()?
You are using viewmodels, so you should map the db data to your viewmodels first:
public ActionResult Index()
{
var teams = db
.Teams
.Include("Players") // Assuming your Team entity has a collection of Players
.SelectMany(t => new TeamVM {
ID = t.ID,
// etc..
})
.ToList();
return View(new TeamViewModel { Teams = teams });
}
model:
public class TeamVM
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime? LastActivity { get; set; }
public IList<PLayerVM> PlayerVM { get; set; }
public int NumberPlayers {
get { return PlayerVM.Count(); }
}
}
Then in your view:
#model MyProject.Models.TeamViewModel
<table>
#foreach(var team in Model.Teams.ToList()) {
<tr>
<td>#team.Name</td> // Name
<td>#team.NumberPlayers</td> // Playercount
<td>#team.PlayerVM.Max(p => p.LastActivity).LastActivity</td> // Last edited
</tr>
}
</table>

Get Navigation Properties id's in action method

I have 3 models names images,game and imageviewmodel
public class game
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<images> Image { get; set; }
}
public class images
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[DataType(DataType.ImageUrl)]
public string Image1Url { get; set; }
public virtual game Game { get; set; }
}
public class ImageViewModel
{
[Required]
[DataType(DataType.Upload)]
public HttpPostedFileBase ImageUpload { get; set; }
public virtual game Game { get; set; }
}
public class GameDb : DbContext
{
public DbSet<game> Games { get; set; }
public DbSet<images> Images { get; set; }
}
My view is strongly typed view of imageviewmodel . I have a dropdown list there with all games filled Here is my GET create method
public ActionResult Create()
{
ViewBag.GameId = new SelectList(db.Games, "Id", "Name");
return View(new ImageViewModel());
}
my dropdown is filled with GenreId
<div class="editor-field">
#Html.DropDownList("GameId","Select an Item")
</div
On my POST create method I want to access dropdown value id to insert in image table
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ImageViewModel model)
{
}
I am unable to access game id of drop down list.I am doing like this
var img=new images{
Game.( no intellisense) =model.Game.id,
};
How do I resolve that need some help.
First of all consider follow the naming convensions when you name your classes.
Second, consider using DropDownListFor helper method instead of DropDownList
And finally you have to create new Game object instance before set it's id:
var img = new images
{
Game = new game { Id = model.Game.Id }
};

Accessing Navigation Properties in a View

I have a Controller action the receives 2 URL parameters, which are foreign keys for the data model:
public ActionResult Create(SurveyResponseModel surveyresponsemodel, int MemberId, int ProgramId)
{
surveyresponsemodel.MemberId = MemberId;
surveyresponsemodel.ProgramId = ProgramId;
return View(surveyresponsemodel);
}
Here is the data model:
public class SurveyResponseModel
{
[Key]
public int ResponseId { get; set; }
public int MemberId { get; set; }
public int ProgramId { get; set; }
// "If yes, what changes did you make? Mark all that apply."
[DisplayName("Did you make any changes in your practice, research, or administration activities as a result of participating in this CME activity?")]
public string CmeChanges { get; set; }
[DisplayName("Better patient follow-up")]
public bool PatientFollowUp { get; set; }
public virtual SurveyProgramModel SurveyProgramModel { get; set; }
public virtual PersonModel PersonModel { get; set; }
And the Data Model for "SurveyProgramType"
public class SurveyProgramModel
{
[Key]
public int ProgramId { get; set; }
public int ProgramYear { get; set; }
public int ProgramStatusId { get; set; }
public string ProgramTitle { get; set; }
public int ProgramTypeId { get; set; }
public virtual SurveyProgramTypeModel ProgramType { get; set; }
public virtual ProgramStatusModel ProgramStatusModel { get; set; }
}
What I want to be able to do in my view, is retrieve the ProgramTitle by the URL parameter that is passed for ProgramId. So the view looks something like:
<div class="editor-label">
#Model.SurveyProgramModel.ProgramTitle
</div>
However, #Model.SurveyProgramModel.ProgramTitle is throwing an exception because it is null. I'm thinking I have my navigation property set up incorrectly. Any idea what that is?
Shouldn't you return your view model to the view?
public ActionResult Create(
SurveyResponseModel surveyresponsemodel) //, int MemberId, int ProgramId)
{
// MemberId and ProgramId arguments do not need to be defined
// They will be picked up my MVC model binder, since there are properties
// with the same name in SurveyResponseModel class
//surveyresponsemodel.MemberId = MemberId;
//surveyresponsemodel.ProgramId = ProgramId;
surveyresponsemodel.SurveyProgramModel = new SurveyProgramModel(); // new line
return View(surveyresponsemodel); // <- return your view model here
}
without passing the model to the view, you cant access the properties of the model in your view. thats the possible cause of the error.
public ~ActionResult PassModel(DemoModel _model, int id)
{
// your code goes here....
return View(_model); // pass the model to view ..so you can work on your model
}

ViewModel adding custom class to another class

I created this viewmodel:
public class PlayerViewModel
{
PlayerRepository repo = new PlayerRepository();
public Player Player { get; set; }
public int SelectedUserID { get; set; }
public SelectList Users { get; set; }
public PlayerViewModel()
{
Player = new Player();
}
public PlayerViewModel(int id)
{
Player = repo.Retrieve(id);
Users = new SelectList(repo.GetUsers());
SelectedUserID = 0;
}
}
this I have in view:
#Html.DropDownListFor(x => x.SelectedUserID, Model.Users)
#Html.ValidationMessageFor(x => x.SelectedUserID)
and this in controller:
[Authorize]
public ActionResult Upravit(int id)
{
var playerview = new PlayerViewModel(id);
return View(playerview);
}
[Authorize,HttpPost]
public ActionResult Upravit(int id, PlayerViewModel playerView)
{
if (ModelState.IsValid)
{
playerView.Player.User = usRepo.GetUserById(playerView.SelectedUserID);
repo.Save(playerView.Player);
return RedirectToAction("Podrobnosti", new { id = playerView.Player.PlayerID });
}
return View(playerView);
}
Now I have problem that " The field SelectedUserID must be a number." and I have in dropdownlist UserName. I modified this many times, I tried with Dictionary and other ways but everyway has some problem. So I want just ask for best way to add custom class User to class Player.
Player class:
public class Player
{
// pokud použijeme virtual a vlastností tak nám EF rozšíří o další možnosti jako lazy loading a další
[Key]
public int PlayerID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Surname { get; set; }
public string PhotoUrl { get; set; }
public string Post { get; set; }
public virtual Team Team { get; set; }
public virtual User User { get; set; }
// public int UserID { get; set; }
//public virtual ICollection<Article> Articles { get; set; }
// Here could be next things as number, ...
}
Thanks
Use this constructor instead:
http://msdn.microsoft.com/en-us/library/dd505286.aspx
public SelectList(
IEnumerable items,
string dataValueField,
string dataTextField
)
Something like this:
Users = new SelectList(repo.GetUsers(),"UserID", "UserName");

Categories

Resources