Gallery Model with Picture and Comments in MVC3 - asp.net

I've just learnt how to upload pictures and bring them in view Model.
Now I'm trying to Add comments to the pictures. That means a picture can have more comments.
So I created 2 Tables, called "Gallery" and "Comment". They are related by 'One to Many'..
My model looks like that..
public class GalleryEntries
{
public List Entries { get; set; }
}
public class GalleryEntry
{
public Gallery GalleryImage { get; set; }
public List Comments { get; set; }
}
And the controller looks so..
GalleryDataContext GalleryDB = new GalleryDataContext();
public ActionResult Index()
{
GalleryEntries model = new GalleryEntries();
GalleryEntries galleryentries = new GalleryEntries();
foreach (Gallery gallery in GalleryDB.Galleries)
{
GalleryEntry galleryentry = new GalleryEntry();
galleryentry.Comments = GalleryDB.Comments.Where(c => c.BildID == gallery.ImageID).ToList();
galleryentry.GalleryImage = gallery;
galleryentries.Entries.Add(galleryentry);
}
return View(model);
}
But it doesn't work. :(
It displays "Object reference not set to an instance of an object" at the line where "galleryentries.Entries.Add(galleryentry) stands.. How can I solve this problem?

I think the problem is that you don't initialize the GalleryEntries.Entries property anywhere ... so you're attempting to add galleryentry to a List that does not exist yet, hence the NullReferenceException.
You could initialize Entries in the constructor:
public class GalleryEntries
{
public IList<GalleryEntry> Entries { get; set; }
public GalleryEntries() {
Entries = new List<GalleryEntry>();
}
}

Related

Mapping SQL View in EF Core 5 - SaveChanges

I'm trying to add a view as a Navigation Property of an entity.
public class Schedule
{
public int Id { get; set; }
public decimal ScheduledQuantity { get; set; }
public ScheduleDetails ScheduleDetails { get; set; }
}
public class ScheduleDetails
{
public int ScheduleId { get; set; }
public decimal BadQuantity { get; set; }
public Schedule Schedule { get; set; }
}
with mappings:
public class ScheduleDetailMap : IEntityTypeConfiguration<ScheduleDetails>
{
public void Configure(EntityTypeBuilder<ScheduleDetails> builder)
{
builder.ToView("vwScheduleDetails", "ShopOrders");
builder.HasKey(t => t.ScheduleId);
builder.HasOne(p => p.Schedule).WithOne(s => s.ScheduleDetails);
}
}
public class ScheduleMap : IEntityTypeConfiguration<Schedule>
{
public void Configure(EntityTypeBuilder<Schedule> builder)
{
builder.ToTable("Schedules");
builder.HasKey(t => t.Id);
builder.Property(t => t.Id).UseIdentityColumn();
}
}
when I query it works fine. However if I add a new Schedule record.
var schedule = new Schedule
{
ScheduledQuantity = 100,
ScheduleDetails = new ScheduleDetails()
};
context.Schedules.Add(schedule);
context.SaveChanges();
I get an exception saying " The entity type 'ScheduleDetails' is not mapped to a table, therefore the entities cannot be persisted to the database. Use 'ToTable' in 'OnModelCreating' to map it."
Is there anyway to get EF to ignore saving this 'entity'?
This is kind of an old question, but for anyone having similar issues - in my case the problem lied in navigation properties in my view. I had some leftover properties in view's class, because its code was copied from other entity. By removing those properties, the error was gone.
This doesn't really help if you want to use navigation properties in your code, but it may help someone to continue their search.

Transferring data entities from a DataService class to a view in MVC

I'm trying to learn MVC. I'm having some trouble understanding how to return data from my DataService class to my view. Here's the structure of my solution so far:
The solution contains two projects and a database. The first project is my DataService project that contains my Entity Model and my service class called AppDataService.
The second project is the website itself. It contains my HomeController, an Index view, and my inventory model which contains two models: An Item and the DB Context for Items called Catalog.
The goal of the application is to create a simple application that displays the inventory of a stock room and displays the information for a user. It's not for a homework assignment so there are no predefined objectives. I'm just trying to learn the MVC convention on my own. I realize that this is a pretty basic question, but I'm kind of at a dead end.
Here's my code:
AppDataServices:
public class AppDataService:IAppDataService
{
public Inventory GetItem(string srch)
{
Inventory item = null;
using (var data = new WCSDatabaseEntities())
{
item = data.Inventories.FirstOrDefault(x => x.Name == srch);
}
return item;
}
public List<Inventory> GetCatalog()
{
List<Inventory> catalog = null;
using (var data = new WCSDatabaseEntities())
{
catalog = data.Inventories.ToList();
}
return catalog;
}
public void Dispose()
{
}
}
My application's models:
public class Item
{
public int MediaId { get; set; }
public string Name { get; set; }
public int InStock { get; set; }
public decimal Price { get; set; }
public string Manufacturer { get; set; }
}
public class InventoryDbContext : DbContext
{
public DbSet<Item> Catalog { get; set; }
}
Currently, nothing I have tried has worked so my home controller's index action just returns the view, and the view currently doesn't accept a model. Can anyone help to explain how I take the returned entities and attach them to a model to send to the view? Thanks in advance! I realize this is a really basic question.
Edit: Here is the Home Controller.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
At your most basic level you want something like:
public class HomeController : Controller
{
public ActionResult Index()
{
// Assuming you're not using an IoC container.
AppDataService appDataService = new AppDataService();
Inventory item = appDataService.GetItem("Albatross");
IndexViewModel model =
new IndexViewModel()
{
Name = item.Name
};
return View(model);
}
}
Create yourself a folder called /ViewModels/Home in the root of your MVC project and add a class called IndexViewModel:
public class IndexViewModel
{
public string Name { get; set; }
}
Then in your view (Index.cshtml):
#model MyNamespaceChangeMe.ViewModels.Home.IndexViewModel
<p>Here's your #Model.Name from the stock room.</p>

How to bind bropdown list in Razor View (If view is not bound with any model)

Can anybody suggest me how bind a dropdown list in MVC Razor view. I am using MVC 4. I have a view that is not bound with any model class.
public class Util {
public List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
public class EmployeeType {
public int ID { get; set; }
public string Text { get; set; }
}
I have this sample code. I am new to MVC Now after this I don't know how to bind the collection returned by GetEmployeeTypes() Method to a dropdown list
Your class with method
public class Util {
public List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
Your model class with properties
public class EmployeeType {
public int ID { get; set; }
public string Text { get; set; }
}
This is sample action
public ActionResult ViewName()
{
Util xxx=new Util();
List<SelectList> SelectedItems =new List<SelectList>();
List<EmployeeType> items =xxx.GetEmpTypes();
foreach (var t in items )
{
SelectListItem s = new SelectListItem();
s.Text = t.Text;
s.Value = t.ID;
SelectedItems.Add(s);
}
ViewBag.xxxxx= SelectedItems;
return view();
}
In View
#Html.DropDownList("xxxxx", new SelectList(ViewBag.xxxxx, "Text", "Value"))
This above code just like a key, i don't tested for that code ran successfully. you can get some idea for how to bind dropdown from my code.
I had a Class like this to get all EmployeeTypes
public class Util
{
public List<EmployeeType> GetEmpTypes()
{
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
}
public class EmployeeType
{
public int ID { get; set; }
public string Text { get; set; }
}
In Controller I have written code to get the List of Employee Types
Util obj = new Util();
var v = obj.GetEmpTypes();
ViewBag.EmployeeTypes = v;
return View();
In the View I have written code to bind dropdown.
#Html.DropDownList("EmployeeTypes",new SelectList(ViewBag.EmployeeTypes,"ID","Text"));
Thanks #Ramesh Rajendran ( Now I understood the concept to bind dropdown)
*strong text*you should create the model selectlist like here:
public static List<EmployeeType> GetEmpTypes() {
return (new List<EmployeeType>(){
new EmployeeType(){ID=101, Text="Permanent"},
new EmployeeType(){ ID=102, Text="Temporary"}
});
}
public static SelectList GetMyEmpTypes
{
get { return new SelectList(GetEmpTypes(), "ID", "Text"); }
}
then you access this method in dropdown list like
#Html.DropDownList("Name",yourProjectNameSpace.Util.GetMyEmpTypes())
when you will submit your form then it value bidden with Name get post to controller.
it is not necessary to bind with model class.you can receive the value on controller with the name that you have given in view like:
#Html.DropDownList("Name",yourProjectNameSpace.YourClass.GetEmpTypes())
Now you can recive the name value at controller like:
public ActionResult test(String Name)
{
return view();
}
and make your method static i.e GetEmpTypes() so that you can access it from view.

EditorFor + foreach + complex type

I have 2 classes:
public class Poll
{
//...
public virtual ICollection<Answer> Answers { get; set; }
}
public class Answer
{
public int Id { get; set; }
[Required]
public string Content { get; set; }
private int _amount = 0;
public int Amount
{
get { return _amount; }
set { _amount = value; }
}
}
And I need to make an Editor View.
If I try this:
#foreach (var answer in Model.Answers)
{
#Html.EditorFor(model => answer)
}
It shows everything for editing, but doesnt save changes. Controller recieves poll.Answers = null
That is because you are bypassing the advanced ID/Name generation that editors do. Since you are rendering each editor separately without any context/scope metadata, the editor renderer simply renders itself as if the model passed to it were the top-level model.
Check this question for more info:
using Html.EditorFor with an IEnumerable<T>

MVC3 binding querystring parameter to deep object property

My domain is setup similar to
public class Pagination
{
public int? Page { get; set; }
}
public class IndexViewModel
{
public Pagination Pagination { get; set; }
}
public class HomeController : Controller
{
public ActionResult Index(IndexViewModel model, Pagination pg, string page)
{
return View(model);
}
}
When I navigate to /?Page=5 I would expect 5 to be the value of model.Pagination.Page to be 5 also, however it appears MVC does not bind query parameters more than 1 layer deep.
What can do I do to change this?
Or is changing this setting up more trouble than it's worth? And I should just do
public class HomeController : Controller
{
public ActionResult Index(IndexViewModel model, Pagination pg, string page)
{
model.Pagination = pg;
return View(model);
}
}
*Note the triple parameters are there to illustrate that it won't fill IndexViewModel but it fills both of the other parameters since they're 0 or 1 layer deep.
Shouldn't your method signature be...
public ActionResult Index(int? page)
{
var model = new IndexViewModel{
Pagination = new Pagination { Page = page ?? 1 } };
if(page.HasValue)
model.Stuff = StuffGenerator
.GetStuff()
.Skip(page.Value * _pageSize)
.Take(_pageSize);
else
model.Stuff = StuffGenerator.GetStuff().take(_pageSize);
return View(model);
}
Your example sounds like a GET but looks like a POST.

Resources