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)
Related
I have this piece of code. My intention is to create field, which I can pass as textValue to SelectList object.
Here are my two entities:
public class Ski
{
public int ID { get; set; }
public int BrandID { get; set; }
public virtual Brand Brand { get; set; }
[NotMapped]
public string BrandName
{
get
{
return this.Brand.Name.ToString();
}
}
}
public enum BrandName
{
Blizzard, MCAD, ATOMIC
}
public class Brand
{
public int ID { get; set; }
public BrandName Name { get; set; }
}
And SelectList initialization
ViewBag.SkiID = new SelectList(db.Skis, "ID", "BrandName");
But such a solution does not seem to work.
How can such a thing be implemented then?
Error says that I have an associated DataReader.
Create this view model:
public class SkiViewModel
{
public string Text{ get; set; }
public int Value{ get; set; }
}
and change your code:
var result = db.Skis.Select(x => new SkiViewModel()
{
Text = x.BrandName.Name ,
Value = ID
});
ViewBag.Skis = new SelectList(result, "Value", "Text");
and in view:
#Html.DropDownList("Value", new SelectListItem(ViewBag.Skis , "Value", "Text"))
I have my ViewModel, and I have my controller to display from the ViewModel correctly, however I'm not sure how I would make the ViewModel editable, as to send the edited data back to the Model. I only want to edit the OrderArchiveViewModel, not the details
ViewModel;
public class OrderArchiveViewModel
{
public int OrderId { get; set; }
public System.DateTime OrderDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public decimal Total { get; set; }
public bool HasBeenShipped { get; set; }
public List<OrderDetailArchive> Details { get; set; }
}
public class OrderDetailArchive
{
public string Title { get; set; }
public string Colour { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}
Controller;
[Authorize(Roles = "Administrator")]
public ActionResult Index()
{
List<T_shirt_Company_v3.ViewModels.OrderArchiveViewModel> list = (from o in new TshirtStoreDB().Orders
.OrderBy(o => o.OrderDate)
.Select(o => new OrderArchiveViewModel()
{
OrderId = o.OrderId,
Address = o.Address,
FirstName = o.FirstName,
LastName = o.LastName,
City = o.City,
OrderDate = o.OrderDate,
PostalCode = o.PostalCode,
Total = o.Total,
HasBeenShipped = o.HasBeenShipped,
Details = (from d in o.OrderDetails
select new OrderDetailArchive
{
Colour = d.Product.Colour,
Quantity = d.Quantity,
Title = d.Product.Title,
UnitPrice = d.UnitPrice
}).ToList()
}).ToList()select o).ToList();
ViewBag.ShippedMessage = list.Where(w => w.HasBeenShipped).Any() ? "Order has been shipped" : "Order is being processed";
return View(list);
}
I can suggest you to make an another two actions.
public ActionResult Edit(int id)
where you will get the Order by it's Id, map to ViewModel and pass it to the view where you will have textboxes for editing. Create another one Action for accepting post request with updated model:
[HttpPost]
public ActionResult Edit(OrderArchiveViewModel model)
When the the edit page is submitted you will have a updated model with the new data, then find your model in database by Id and update the properties.
Can u send the code of your View to get more clarification?
The already given answer could be done by redirect to a page for editing purpose.
Do you want to show the Editing fields above the Grid?
For this purpose, you can add New ViewModel like
public class NewViewModel
{
public OrderArchiveViewModel OrderArchiveViewModel { get; set; }
public List<OrderArchiveViewModel> OrderArchiveViewModelList { get; set; }
}
And you can send data using this NewViewModel to View containing both editable OrderArchiveViewModel depending on the Id and also the List of OrderArchiveViewModel by assigning the list present in Index() action.
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>
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 }
};
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.