Get Navigation Properties id's in action method - c#

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 }
};

Related

Display specific field found by Id Entity Framework 6

I have thse two classes. The code works, I can add a Movie to an actor and viceversa.
However, on the frontend side I cannot display the Name of the entity I'm adding, I can only display the Id number.
If I use a DropDownListFor I can display the names of the actors but I can only save an actor through the Id field.
How do I make it so that I display only the actor name and still save it on the database?
public class Movie
{
[Key]
public int Id { get; set; }
public string Title { get; set; }
public int ActorId { get; set; }
[ForeignKey("ActorId")]
public ICollection<Actor> Actors { get; set; }
public int DirectorId { get; set; }
[ForeignKey("DirectorId")]
public Director Director { get; set; }
}
public class Actor
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int MovieId { get; set; }
[ForeignKey("MovieId")]
public ICollection<Movie> CreditedMovies { get; set; }
}
For your scenario you required view model with properties of DD as well.
MovieViewModel.cs
public class MovieViewModel
{
public Movie Movie{get;set;}
public List<SelectListItem> ActorDD {get;set;}
}
using above view model you will need to bind your DD like below
Controller
public ActionResult Home()
{
MovieViewModel model = new MovieViewModel();
model.ActorDD.Add(new SelectListItem { Text = "Actor1", Value = "1" });
model.ActorDD.Add(new SelectListItem { Text = "Actor2", Value = "2" });
model.ActorDD.Add(new SelectListItem { Text = "Actor3", Value = "3" });
return View(model);
}
Your view look like below.
Razor.cshtml
#Html.DropDownListFor(m=>m.Movie.ActorId, model.ActorDD)

Class Id from view to other class/view MVC 4

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>

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>

Populating Drop Down Box with Db Data

Have managed to get this working now. As expected it was simpler than I was making it. Hopefully this can save someone looking to do the same thing some time in the future. Have amended code below to the working code.
Thanks for the help all.
Partial View Returning the Drop Down:
#model Project.Models.Item
#Html.DropDownListFor(m=>m.CategoryId,new SelectList(ViewBag.CategoryList,"CategoryId","CategoryName"),"Select")
Controller:
[HttpGet]
public ActionResult Create()
{
ViewBag.CategoryList = db.Categorys.ToList();
ViewBag.DesignerList = db.Designers.ToList();
return View();
}
item Model:
public class Item
{
public Item()
{
this.Images = new List<Image>();
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[ScaffoldColumn(false)]
public int ItemId { get; set; }
public int CategoryId { get; set; }
public int DesignerId { get; set; }
public int ImageId { get; set; }
[Required(ErrorMessage="Please Enter the Items Name ")]
[StringLength(150,MinimumLength=2)]
public string ItemName { get; set; }
[Required(ErrorMessage = "Price Cannot be Negative ")]
[Range(0,999999.99)]
public decimal ItemPrice { get; set; }
[StringLength(1000,MinimumLength=2)]
public string ItemDescription { get; set; }
[Range(4,22)]
public int ItemSize { get; set; }
//Files Being Uploaded by the User
public HttpPostedFileBase[] Files { get; set; }
public virtual Category Category { get; set; }
public virtual Designer Designer { get; set; }
public virtual List<OrderDetail> OrderDetails { get; set; }
public virtual List<Image> Images { get; set; }
}
Category Model:
public class Category
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[ScaffoldColumn(false)]
public int CategoryId { get; set; }
[Required(ErrorMessage="Must Supply a Category")]
[StringLength(250,MinimumLength=1)]
public string CategoryName { get; set; }
}
I don't know if I'm missing something in your code but I can't see any piece of code where you are populating the ViewBag.Categories collection.
In documentation second parameter is more about having Collection (IEnumerable) of SelectListItem objects than having SelectList collection of your entity objects. That is causing problem with populating the dropdown control.
Next thing that I noticed is that the first parameter (the expression) is selecting the Category object - I believe that is impossible to do with select list which stores only Value(Key) and the Text. You should use here integer property named like 'SelectedCategory'
check this code
it should be
#Html.DropDownListFor(model=>model.Category.CategoryName,ViewBag.Categories as SelectList,"-- Select Category--")
also in controller set ViewBag.Categories with your db values.

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