I'm creating a page that will display 6 blogs that were created in the passed 7 days. The blog contains an image and multiple comments
Here is the Blog model
public class Blog
{
public int BlogID { get; set; }
public int likes { get; set; }
public int ImageID { get; set; }
public Boolean removed { get; set; }
public DateTime dte_created { get; set; }
public DateTime? dte_modified { get; set; }
public virtual Image Image { get; set; }
public virtual ICollection<Comment> Comment { get; set; }
}
And here's the blogContent.
public class Image
{
public int ImageID { get; set; }
public string img_path { get; set; }
public string Description { get; set; }
public DateTime dte_created { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Commentation { get; set; }
public int likes { get; set; }
public int BlogID { get; set; }
public DateTime dte_created { get; set; }
public DateTime? dte_modified { get; set; }
public Boolean removed { get; set; }
//public virtual int Account_ID { get; set; }
public virtual Blog Blog { get; set; }
}
Here is the controller
private ACaptureDB db = new ACaptureDB();
public ViewResult Index()
{
ViewBag.Message = "ArchiCapture";
var dateCheck = DateTime.Now.AddDays(-7);
var results = from r in db.Blog
where r.dte_created >= dateCheck
select r;
return View(results);
}
and my View.
#model IEnumerable<ACapture.Models.Blog>
#{
ViewBag.Title = "Home Page";
}
<div class="Forum">
<p>The Forum</p>
<form class="Forum" runat="server">
#foreach (var item in Model)
{
<div class="ForumChild"><img src="#item.Image.img_path" alt="Not Found" />
<br />
<table>
?????????
</table>
</div>
}
</form>
</div>
How would I retrieve all the comments that are linked to the blog?
You should be able to loop over the Comments collection in your model blog object:
<table>
#foreach(var comment in Model.Comments) {
<tr>
<td>#comment.Commentation</td>
....
</tr>
}
</table>
Related
I have generated Models classes using Entity Framework.
This is what I got:
public partial class Employees
{
public Employees()
{
this.Employees1 = new HashSet<Employees>();
this.Vacations = new HashSet<Vacations>();
}
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Phone { get; set; }
public string JobTitle { get; set; }
public int ManagerID { get; set; }
public string LastUpdatedBy { get; set; }
public Nullable<System.DateTime> LastUpdatedDate { get; set; }
public bool Status { get; set; }
public virtual ICollection<Employees> Employees1 { get; set; }
public virtual Employees Manager { get; set; }
public virtual ICollection<Vacations> Vacations { get; set; }
}
Then I've created View Model for that class:
public class EmployeeViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Phone { get; set; }
public string JobTitle { get; set; }
public int ManagerID { get; set; }
public string ManagerFullName
{
get
{
return FirstName + " " + LastName;
}
}
public bool Status { get; set; }
public virtual ICollection<Employees> Employees1 { get; set; }
public virtual Employees Manager { get; set; }
}
In EmplyeeControler class I have action:
public ActionResult Create()
{
EmployeeViewModel employeeVM = new EmployeeViewModel();
ViewBag.Employees1 = new SelectList(employeeVM.Employees1, "EmployeeID", "ManagerFullName");
return View(employeeVM);
}
And view:
<div class="editor-label">
#Html.LabelFor(model => model.ManagerID, "Manager")
</div>
<div class="editor-field">
#Html.DropDownList("ManagerID", "--- Select Manager ---")
#Html.ValidationMessageFor(model => model.ManagerFullName)
</div>
But I am receiving error on line:
Value cannot be null. Parameter name: items
ViewBag.Employees1 = new SelectList(employeeVM.Employees1, "EmployeeID", "ManagerFullName");
What is wrong in my code?
<div class="editor-label">
#Html.LabelFor(model => model.ManagerID, "Manager")
</div>
<div class="editor-field">
#Html.DropDownListFor(x => x.ManagerID, (IEnumerable<SelectListItem>)ViewBag.Employees1,"--- Select Manager ---"));
#Html.ValidationMessageFor(model => model.ManagerFullName)
</div>
More Details See this link
i created a dropdown list in MVC page,i want when changed id,new data pass to Action with below code:
#if (ViewBag.IdType==1)
{
#Html.DropDownListFor(m => m.Citycode, new SelectList(ViewBag.ResultList as System.Collections.IEnumerable, "Citycode", "CityName","1"))
#Html.ValidationMessageFor(model => model.Citycode)
}
else
{
#Html.DropDownListFor(m => m.IDReshteh, new SelectList(ViewBag.ResultList as System.Collections.IEnumerable, "IDReshteh", "ReshteName",Model.IDReshteh),"Fselect")
#Html.ValidationMessageFor(model => model.IDReshteh)
}
<input type="hidden" id="SelValue" value="1"/>
<input type="submit" value="Submit" />
</p>
/*<input type="hidden" name="HDcity" id="HDcity" />*/
<div id="LoadData">
#Html.Action("selVahedListAjax", new { IdReshte = ViewBag.ChooseItem, IdCity = Model.IDReshteh })
</div>
Model:
public class TInfo
{
[Key]
public int Id { get; set; }
[Required]
public string Scode { get; set; }
[Required]
public string SName { get; set; }
[Required]
public string TName { get; set; }
public string ModirName { get; set; }
public string FZamineh { get; set; }
public string TAddress { get; set; }
public string PcodeSh { get; set; }
public string TelcodeSh { get; set; }
public string FaxcodeSh { get; set; }
public string DAddress { get; set; }
public string PcodeDa { get; set; }
public string TelcodeDa { get; set; }
public string FaxcodeDa { get; set; }
public string WebsiteAddress { get; set; }
public string EmailAdd { get; set; }
public string TablighatPic { get; set; }
[Required]
public int Citycode { get; set; }
[ForeignKey ("Citycode")]
public Lcity City { get; set; }
[Required]
public int IDReshteh { get; set; }
[ForeignKey("IDReshteh")]
public RFaaliat Reshteh { get; set; }
}
My controller:
//If IdType=1 then user clicked on Reshteh But if IdType=2 then user clicked on city
public ActionResult selVahedList(int IdType, int IdChoose)
{
ViewBag.ChooseItem = IdChoose;
ViewBag.IdType = IdType;
if (IdType == 1)
ViewBag.ResultList = Dbcon.Lcitys.ToList();
else
ViewBag.ResultList = Dbcon.RFaaliats.ToList();
return View();
}
public ActionResult selVahedListAjax(int IdReshte,int IdCity )
{
ViewBag.Reshteh = IdReshte;
var res = Dbcon.TaavoniInfos.Where(m => m.IDReshteh == IdReshte && m.Citycode ==?);//Idont know what should put here
return PartialView(res);
}
my problem is i cant get and pass selected item in drop down and update data in page. please help me.
thanks a lot
To make things simple, I have 3 entities (one to many, left to right):
COURSE -> MODULE -> CHAPTER
A course can have multiple modules and a module can have multiple chapters.
All I have in the controller is this:
Course course = db.Courses.Find(id);
return View(course);
I was trying to use an include but it doesn't seem to evaluate (this doesn't seem to work: Course course = db.Courses.Include("Modules").Find(id);)
So I let it be. In my view, I have this nested List:
<ul>
#foreach (var item in Model.Modules)
{
<li>#module.Title
<ul>
#foreach (var item in module.Chapters)
{
<li>#chapter.Title</li>
}
</ul>
</li>
}
</ul>
Will this work automatically?
Lastly, I applied a SortOrder column so I could arrange the child entities. I know that this should be done in the query, but how can I do this?
Thanks! Any piece of information or advise would be highly appreciated.
UPDATE
Course Class
public partial class Course
{
public Course()
{
this.Modules = new HashSet<Module>();
this.Assets = new HashSet<Asset>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Author { get; set; }
public System.DateTime CreateDate { get; set; }
public bool IsDeleted { get; set; }
public int IndustryId { get; set; }
public virtual ICollection<Module> Modules { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
public virtual Industry Industry { get; set; }
}
Module Class
namespace RocketLabs.Models
{
using System;
using System.Collections.Generic;
public partial class Module
{
public Module()
{
this.Chapters = new HashSet<Chapter>();
this.Assets = new HashSet<Asset>();
}
public int Id { get; set; }
public string Title { get; set; }
public System.DateTime CreateDate { get; set; }
public int CourseId { get; set; }
public bool IsDeleted { get; set; }
public short SortOrder { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Chapter> Chapters { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
public virtual Exam Exam { get; set; }
}
}
Chapter Class
namespace RocketLabs.Models
{
using System;
using System.Collections.Generic;
public partial class Chapter
{
public Chapter()
{
this.Assets = new HashSet<Asset>();
}
public int Id { get; set; }
public string Title { get; set; }
public int ModuleId { get; set; }
public string Notes { get; set; }
public short SortOrder { get; set; }
public System.DateTime CreateDate { get; set; }
public bool IsDeleted { get; set; }
public virtual Module Module { get; set; }
public virtual ICollection<Asset> Assets { get; set; }
}
}
you can do this:
var course = db.Courses
.Include(i => i.Modules.Select(s => s.Chapter))
.Single(s=>s.Id == id);
return View(course);
And your loop:
<ul>
#foreach (var module in Model.Modules)
{
<li>#module.Title
<ul>
#foreach (var chapter in module.Chapters)
{
<li>#chapter.Title</li>
}
</ul>
</li>
}
</ul>
As for sorting, we can include .OrderBy() on your query but you need to elaborate what child entities you want sorted and by what fields.
I have a class, Event, and i want to be able to have images on the event page. I have defined the image class but am now sure how i can upload the image. I want to be able to store the image in the database.
public class Event
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Address { get; set; }
public string AddressTwo { get; set; }
public virtual Person Owner { get; set; }
public DateTime Date { get; set; }
public virtual Image Image { get; set; }
}
public class Image
{
public int Id { get; set; }
public string Name { get; set; }
public string AlternateText { get; set; }
public virtual string CssClass { get; set; }
public Byte[] File { get; set; }
}
If you want to handle file uploads you should use the HttpPostedFileBase type to represent the image and not a byte array:
public class Image
{
public int Id { get; set; }
public string Name { get; set; }
public string AlternateText { get; set; }
public virtual string CssClass { get; set; }
public HttpPostedFileBase File { get; set; }
}
then in your view you will use a file input:
#model Event
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div>
#Html.LabelFor(x => x.Image.File)
#Html.TextBox(x => x.Image.File, new { type = "file" })
</div>
... some other fields
<button type="submit">OK</button>
}
and finally you will have the controller action to which the form will be posted and which will save the file:
[HttpPost]
public ActionResult Upload(Event model)
{
if (model.Image != null && model.Image.ContentLength > 0)
{
// an image was selected by the user => process and store it into the database
}
...
}
You might also find the following blog post useful.
A brief description of what I am doing. I am creating a rather crude IS Asset tracking database using ASP MVC 3 and EF Code First approach. I can create a new asset. I can view the details on an asset. I can even display the edit view and edit the AssetTag. However the record will not update any of the other fields. If I edit the LocationName for instance. It will act like it is posting and return me to the Index view, but the record never actually posts the change.
I have created the Model below
public class AssetModel
{
public int id { get; set; }
public string AssetTag { get; set; }
public virtual Location Location { get; set; }
public virtual Hardware Hardware { get; set; }
public virtual Software Software { get; set; }
public virtual User User { get; set; }
}
public class Location
{
public int LocationId { get; set; }
public string LocationName { get; set; }
}
public class Hardware
{
public int HardwareId { get; set; }
public string Manufacturer { get; set; }
public string Make { get; set; }
public string Model { get; set; }
}
public class Software
{
public int SoftwareId { get; set; }
public string PublisherName { get; set; }
public string SoftwarePackageName { get; set; }
public string SoftwarePackageVersion { get; set; }
public string SerialNumber { get; set; }
public bool IsVolumeLicense { get; set; } // as in "Yes this is a Vol. Lic. Agreement"
public LicenseAgreement LicenseAgreement { get; set; }
}
public class LicenseAgreement
{
public int LicId { get; set; }
public string VolumeLicenseAgreementCompany { get; set; }
public string AgreementIdentifier { get; set; }
public DateTime VolumeLicenseStartDate { get; set; }
public DateTime VolumeLicenseExpirationDate { get; set; }
public Int16 NumberOfLicenses { get; set; }
}
public class User
{
// may remove this at some time and pull from Active Directory.
// for now we take the easy route.
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
I have this DbDataSet that uses the AssetModel above:
public class AssetContext : DbContext
{
public DbSet<AssetModel> Assets { get; set; }
}
In my AssetController I have this for Edit:
public ActionResult Edit(int id)
{
AssetModel assetmodel = db.Assets.Find(id);
return View(assetmodel);
}
//
// POST: /Asset/Edit/5
[HttpPost]
public ActionResult Edit(AssetModel assetmodel)
{
if (ModelState.IsValid)
{
db.Entry(assetmodel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(assetmodel);
}
And here is the Edit.cshtml
#model ISHelpDesk.Models.AssetModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm("Edit", "Asset")) {
#Html.ValidationSummary(true)
<fieldset>
<legend>AssetModel</legend>
<div class="editor-label">
#Html.LabelFor(model => model.AssetTag)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AssetTag)
#Html.ValidationMessageFor(model => model.AssetTag)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Location.LocationName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Location.LocationName)
#Html.ValidationMessageFor(model => model.Location.LocationName)
</div>
</fieldset>
<p><input type="submit" value="Save"</p>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
your AssetContext should be
public class AssetContext : DbContext
{
public DbSet<AssetModel> Assets { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Hardware> Hardwares { get; set; }
public DbSet<Software> Softwares { get; set; }
public DbSet<LicenseAgreement> LicenseAgreements { get; set; }
public DbSet<User> Users { get; set; }
}
this is registering each of your classes as a table in the DbContext, what you had before showed your DbContext consists only of AssetModel
Update: The issue may be that when you get to the post method of the edit, the Asset is no longer associated with the database Asset it was originally loaded from, have a go at changing it to
public ActionResult Edit(int id)
{
AssetModel assetmodel = db.Assets.Find(id);
return View(assetmodel);
}
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
AssetModel assetmodel = db.Assets.Find(id);
if (TryUpdateModel(assetmodel))
{
db.SaveChanges();
return RedirectToAction("Index");
}
return View(assetmodel);
}
Obviously this may not be the behaviour you want I'm just trying to see if you can get some changes persisted and go from there
Your Model classes should extend DbContext:
public class AssetModel :DbContext{}