I'm quite new to ASP.NET MVC. I am creating a holiday tracking app, and I'm attempting to create a details page for each Employee. I want this page to display a table showing a table of all the holiday request that employee has taken. I've gotten it to work but it only shows only one row.
Here's my models
public partial class Employee
{
public int EmployeeID { get; set; }
public string FullName { get; set; }
public string EmailID { get; set; }
public string Password { get; set; }
public System.DateTime StartDate { get; set; }
public int RoleID { get; set; }
public int ShiftID { get; set; }
public int AreaID { get; set; }
public int DisciplineID { get; set; }
public int SiteID { get; set; }
public int ALCategory { get; set; }
public Nullable<int> HoursTaken { get; set; }
public Nullable<int> AwardedLeave { get; set; }
public Nullable<int> TotalHoursThisYear { get; set; }
public int HoursCarriedForward { get; set; }
public Nullable<int> EntitlementRemainingThisYear { get; set; }
public string Comments { get; set;}
}
Employee Model:
public class EmployeeViewModel
{
public Employee Employee { get; set; }
public HolidayRequestForm HolidayRequestForm { get; set; }
}
Holiday Request Form Model:
public partial class HolidayRequestForm
{
public int RequestID { get; set; }
public int EmployeeID { get; set; }
public System.DateTime StartDate { get; set; }
public System.DateTime FinishDate { get; set; }
public int HoursTaken { get; set; }
public string Comments { get; set; }
public int YearCreated { get; set; }
public int MonthCreated { get; set; }
public Nullable<int> DayCreated { get; set; }
public Nullable<int> YearOfHoliday { get; set; }
public virtual Employee Employee { get; set; }
}
Controller Action:
public ActionResult Details(int? id)
{
Employee employee = db.Employees.FirstOrDefault(emp => emp.EmployeeID == id);
HolidayRequestForm holidayRequestForm db.HolidayRequestForms.FirstOrDefault(emp => emp.EmployeeID == id);
EmployeeViewModel employeeViewModel = new EmployeeViewModel()
{
Employee = employee,
HolidayRequestForm = holidayRequestForm,
};
return View(employeeViewModel);
}
My View is then just a HTML table to display the data from the database.
So the question is how do I display more than one row or entry?? Is it that I'm using FirstorDefault?
You must change Employee Model and declare a list for the Holiday :
Employee Model:
public class EmployeeViewModel
{
public Employee Employee { get; set; }
public List<HolidayRequestForm> HolidayRequestForm { get; set; }
}
Controller Action:
public ActionResult Details(int? id)
{
Employee employee = db.Employees.FirstOrDefault(emp => emp.EmployeeID == id);
List<HolidayRequestForm> holidayRequestForm = db.HolidayRequestForms.Where(emp => emp.EmployeeID == id).ToList();
EmployeeViewModel employeeViewModel = new EmployeeViewModel()
{
Employee = employee,
HolidayRequestForm = holidayRequestForm,
};
return View(employeeViewModel);
}
Related
I'm gonna cut to the chase.
I'm creating a Survey platform, it has 3 models.
Model Survey, it has Many SurveyQuestion which has many SurveyAnswer.
(I can insert all of the values of these models but I dont think it is needed)
public class SurveyAnswer
{
[Key]
public int Id { get; set; }
public string Value { get; set; }
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
Now a problem I'm having is once someone created a survey and another person is starting it, he answers and that's it. How do I show that the next time he comes to an index page? How do I show that "you already submitted this survey"? Do I do that in Controller or in View? I would prefer to that in this action currently (it's a menu for all ongoing surveys).
[HttpGet]
public ActionResult Menu()
{
var survey = Mapper.Map<IEnumerable<Survey>, IEnumerable<SurveyViewModel>>(_unitOfWork.SurveyRepository.Get());
return View(survey.ToList());
}
Put all your validation rules to your AbstractValidator class.
[Validator(typeof(SurveyAnswerValidator))]
public class SurveyAnswer{
[Key]
public int Id { get; set; }
public string Value { get; set; }
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
public class SurveyAnswerValidator : AbstractValidator<SurveyAnswer>
{
public SurveyAnswerValidator()
{
//list your rules
RuleFor(x => x.SubmittedBy).Must(BeUnique).WithMessage("Already
submitted this survey");
}
private bool BeUnique(string submittedBy)
{
if(_context.SurveyAnswers.
FirstOrDefault(x => x.SubmittedBy == submittedBy) == null){
return true;
}
else{
return false;
}
}
}
If you want to check uniqueness in ViewModel you can use Remote.
public class SurveyAnswerVM{
[Key]
public int Id { get; set; }
public string Value { get; set; }
[Remote("HasSubmitted", "ControllerName")]
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
public int QuestionId { get; set; }
public virtual Survey Survey { get; set; }
public virtual SurveyQuestion Question { get; set; }
public string Comment { get; set; }
}
Where HasSubmitted is a method you may create in controller to return true if the user has submitted.
RemoteAttribute
https://msdn.microsoft.com/en-us/library/gg508808(VS.98).aspx
The best solution by vahdet (suggested in comments)
[Index("IX_AnswerQuestion", 2, IsUnique = true)]
[StringLength(36)]
public string SubmittedBy { get; set; }
public int SurveyId { get; set; }
[Index("IX_AnswerQuestion", 1, IsUnique = true)]
public int QuestionId { get; set; }
DB relationship:
1ApplicationUser : n Tickets
1ApplicationUser: n Activities
1Tickets:n Activites
I would like to design above database using code first. However,there's error warning
"Column name 'ApplicationUserId' in table 'Tickets' is specified more
than once."
However, I checked there's only one ApplicationUserId in Table Ticket as shown in below class.
Would anyone please help how to fix it? Thanks.
The entity class are as following:
Ticket Class
public class Ticket
{
public int ID { get; set; }
public Ticket()
{ TicketCreateDate = DateTime.Now; }
public DateTime TicketCreateDate { get; set; }
public int TicketCreateBy { get; set; }
public DateTime TicketCloseDate { get; set; }
public int TicketCloseBy { get; set; }
public DateTime LastTicketUpdateDate { get; set; }
public int LastUpdateBy { get; set; }//Ticket Last Update by
public DateTime TicketAssignedDate { get; set; }
public int TicketAssignedTo { get; set; }
public string TicketType { get; set; }
public string Priority { get; set; }// Ticket priority
public string TicketStatus { get; set; }
public string TicketDescription { get; set; }
public int DeviceUserID { get; set; }
public string DeviceBrand { get; set; }
public string DeviceType { get; set; }
public virtual ICollection<Activity> Activities { get; set; }
public int ApplicationUserID { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
Acitivity Class
public class Activity
{
public int ID { get; set; }
public Activity()
{
CreatedTime = DateTime.Now;
}
public DateTime CreatedTime { get; set; }
public string ActivityDetails { get; set; }
public int ApplicationUserID { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public int TicketId { get; set; }
public virtual Ticket Ticket { get; set; }
}
ApplicationUser Class
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Ticket> Tickets { get; set; }
public virtual ICollection<Activity> Activities { get; set; }
}
Model
public class Cart
{
public int id { get; set; }
public int userId { get; set; }
public int messageId { get; set; }
public virtual List<Product> cart { get; set; }
}
ViewModel
public class cartVM
{
public int id { get; set; }
public int productId { get; set; }
public int userId { get; set; }
public int messageId { get; set; }
public DateTime AddDate { get; set; }
public virtual List<Product> Product{ get; set; }
public List<int> SelectedProductIds { get; set; }
public IEnumerable<SelectListItem> CartChoices { get; set; }
}
Controller function to populate Selectedlist
/// here i can only display productname column, how can i display multiple columns for selectlistitem
private void CartChoices(cartVM model)
{
model.CartChoices = db.Products.Select(m => new SelectListItem
{
Value = ((int)m.ProductId).ToString(),
Text = m.productName
});
}
Razor View to display listbox
<div>
#Html.ListBoxFor(m => m.SelectedProductIds , Model.CartChoices)
</div>
Please look at my sample code below:
public class LoginModel
{
[Key]
public int LoginId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class RegisterModel
{
[Key]
public int RegisterId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
}
There are many records in the cart table added by many users.
But i want to show the own record of a user from the cart table if he is logged in..how can I do this??
You have to insert a foreign-key property to your Cart class:
public class UserModel
{
[Key]
public int LoginId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class Cart
{
[Key]
public int RecordId { get; set; }
public string CartId { get; set; }
public int ProductId { get; set; }
public int Count { get; set; }
public virtual UserModel User { get; set; } // <-- added
}
Then you can use LINQ to query the Cart-items for a specific user:
var cartItems = dbContext.Cart.Where(a => a.User == loggedInUser);
var query = from a in db.Pages
where a.title.Contains(myTitle)
select a;
var item=query.FirstOrDefault();
if(item!=null)
return View(item);
else
return View("NotFound");
I'm learning ASP.NET MVC 4 with Entity Framework (Database First) and ran into a problem that I'm not able to solve.
I have following tables:
Student: To store students information
Course: To store courses running in an institute
StudentCourse: To store which student selected what course
Fees: To store submitted fees by a student corresponding to StudentCourse
Now, I wan't to show course name, course fees, total fees submitted & the pending fees of students
I'm using Entity Framework in the project and trying to execute a query like this:
var feeslist = entities.Fees
.Where(m => m.StudentCourse.status=="pending")
.GroupBy(m => m.StudentCourse.id)
.Select(m => new { StudentCourseId = m.Key, SumOfFees = m.Sum(v => v.fees) });
I want to get Course object instead of StudentCourseId so that i can display the course, its course fees and total fees submitted by student.
In case, I'm listing all of the four class contents:
Student
public partial class Student
{
public Student()
{
this.Leaves = new HashSet<Leave>();
this.StudentCourses = new HashSet<StudentCourse>();
}
public int id { get; set; }
public string first_name { get; set; }
public string middle_name { get; set; }
public string last_name { get; set; }
public string password { get; set; }
public string email { get; set; }
public string gender { get; set; }
public string facebook { get; set; }
public string contact_number { get; set; }
public string address { get; set; }
public string admin { get; set; }
public string college { get; set; }
public string status { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public string descripton { get; set; }
public virtual ICollection<Leave> Leaves { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
Course
public partial class Course
{
public Course()
{
this.CourseContents = new HashSet<CourseContent>();
this.StudentCourses = new HashSet<StudentCourse>();
}
public int id { get; set; }
public string course_name { get; set; }
public int course_fees { get; set; }
public int duration { get; set; }
public string admin { get; set; }
public string status { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public virtual ICollection<CourseContent> CourseContents { get; set; }
public virtual ICollection<StudentCourse> StudentCourses { get; set; }
}
StudentCourse
public partial class StudentCourse
{
public StudentCourse()
{
this.Fees1 = new HashSet<Fee>();
this.Issues = new HashSet<Issue>();
}
public int id { get; set; }
public int student_id { get; set; }
public int course_id { get; set; }
public int fees { get; set; }
public System.DateTime join_date { get; set; }
public string admin { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public string status { get; set; }
public virtual Course Course { get; set; }
public virtual ICollection<Fee> Fees1 { get; set; }
public virtual ICollection<Issue> Issues { get; set; }
public virtual Student Student { get; set; }
}
Fee
public partial class Fee
{
public int id { get; set; }
public int student_course_id { get; set; }
public int fees { get; set; }
public string admin { get; set; }
public System.DateTime createdat { get; set; }
public System.DateTime updatedat { get; set; }
public virtual StudentCourse StudentCourse { get; set; }
}
var feeslist = entities.Fees
.Where(m => m.StudentCourse.status=="pending")
.GroupBy(m => m.StudentCourse.Course)
.Select(m => new { Course = m.Key, SumOfFees = m.Sum(v => v.fees) });