How to get particular row data when click on that particular row button using ASP .NET Core MVC 3 - asp.net-mvc-3

I have two Controllers and their views. The first controller is the applicant controller, In this applicant controller, I have the "add applicant" form. This form link is given to the Second controller(vacancycontroller) view. Now I want to get data on the vacancy positions when I click on the button. Is this possible?
public class Application : IVacancy, IStage
{
[Key]
public int? Id { get; set; }
[Required]
[MinLength(2)]
[MaxLength(50)]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
public string Phone { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public int? Experience { get; set; }
public string Status { get; set; }
public string Resume { get; set; }
[Display(Name = "Vacancy")]
public int? VacancyId { get; set; }
[Display(Name = "Stage")]
public int? StageId { get; set; }
public DateTime DateCreated { get; set; }
[ForeignKey("VacancyId")]
public virtual Vacancy Vacancy { get; set; }
}
This is my application entity.
public interface IVacancy
{
public int? VacancyId { get; set; }
public Vacancy Vacancy { get; set; }
}
[Table("vacancy")]
public class Vacancy
{
[Key]
public int? Id { get; set; }
[Required]
[MinLength(2)]
[MaxLength(50)]
public string Position { get; set; }
[Required]
public string Skills { get; set; }
}
And this is vacancy entity.
When I open the vacancy page and click on add applicant, In add applicant form, VaacancyId Text box fills with the Position of that particular row.This is vacancy page img

Related

Passing more than one model to the view in ASP.NET MVC

I need to pass two models in the same view, however some elements have the same name.
I have two models Employee and HolidayRequestForm and I need to use both of these in the one view which will be a details page for each Employee.
Here is my Employee:
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; }
}
Here is my HolidayRequestForm:
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; }
}
I have tried Creating a separate model that contains all elements to use in the view but I'm not sure how to differentiate elements with the same name eg. Comments Is it even possible to do so?
I would like to use both these models in my view as I'd like to create an Employee Profile page, with their info on the top displaying information about their profile and then holidays they have requested using the holidayrequestform in a table on the bottom of the page.
Write a ViewModel which will contain both Employee and HolidayRequestForm as follows and then pass the ViewModel to the view:
public class EmployeeViewModel
{
public Employee Employee {get; set;}
public HolidayRequestForm HolidayRequestForm {get; set;}
}
Then in your action method:
public ActionResult EmployeeDetails(int id)
{
Employee employee = _dbContext.Employees.FirstOrDefault(emp => emp.EmployeeID == id);
HolidayRequestForm holidayRequestForm = _dbContext.HolidayRequestForms.FirstOrDefault(hrf => hrf.EmployeeID == id);
EmployeeViewModel employeeViewModel = new EmployeeViewModel()
{
Employee = employee,
HolidayRequestForm = holidayRequestForm
}
return View(employeeViewModel);
}
Then in the view, access the model properties as follows:
#model EmployeeViewModel
<p>Full Name: #Model.Employee.FullName</p>

Invalid Column Name Entity guessing a foreign key that isn't there

I don't really understand what's happening here. From my research I gather that entity is trying to guess the name of a foreign key and it's not there, so it's throwing an "Invalid Column Name" error. The problem is that the model/table in question does not have any foreign keys. So I'm really confused.
Here's the code that throws the error:
foreach (TechnologyProjectPlanModel result in results)
{
//get approvers for plan
int id = result.Id;
try
{
List<ApprovalModel> approvers = db.ApprovalModels.Where(m => m.FormId == result.Id).Select(m => m).ToList(); //ERROR HERE
if (approvers != null)
{
result.Approvers = approvers.ToList();
}
}
catch (Exception e)
{
}
}
Here's the ApprovalModel:
public class ApprovalModel
{
[Key]
public int Id { get; set; }
public int ApprovalProcessId { get; set; }
public int FormId { get; set; }
public int UserId { get; set; }
public bool? Approved { get; set; }
}
And here's the TechnologyProjectPlanModel referenced in the foreach loop:
public class TechnologyProjectPlanModel
{
[Key]
public int Id { get; set; }
public int FormId { get; set; }
public int UserId { get; set; }
public string FormType { get; set; }
public int Status { get; set; }
public int Hidden { get; set; }
public DateTime DateSubmitted { get; set; }
public DateTime DateFinalized { get; set; }
public List<QuoteUploadsModel> Quotes { get; set; }
public List<ApprovalModel> Approvers { get; set; }
[Required]
[Display(Name = "Please Select Your School")]
public string School { get; set; }
[Required]
[Display(Name = "Requestor")]
public string Requestor { get; set; }
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
[Phone]
public string PhoneNumber { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email Address")]
[EmailAddress]
public string Email { get; set; }
[Required]
[Display(Name = "Project Title")]
public string ProjectTitle { get; set; }
[Display(Name = "Requested Completion Date")]
public DateTime RequestedCompletionDate { get; set; }
[Required]
[Display(Name = "Project Description")]
public string ProjectDescription { get; set; }
[Display(Name = "Teacher/Room Number")]
public string TeacherGroup { get; set; }
[Display(Name = "1")]
public bool Grade1 { get; set; }
[Display(Name = "2")]
public bool Grade2 { get; set; }
[Display(Name = "3")]
public bool Grade3 { get; set; }
[Display(Name = "4")]
public bool Grade4 { get; set; }
[Display(Name = "5")]
public bool Grade5 { get; set; }
[Display(Name = "6")]
public bool Grade6 { get; set; }
[Display(Name = "7")]
public bool Grade7 { get; set; }
[Display(Name = "8")]
public bool Grade8 { get; set; }
[Display(Name = "9")]
public bool Grade9 { get; set; }
[Display(Name = "10")]
public bool Grade10 { get; set; }
[Display(Name = "11")]
public bool Grade11 { get; set; }
[Display(Name = "12")]
public bool Grade12 { get; set; }
[Display(Name = "Kindergarten")]
public bool Kindergarten { get; set; }
[Display(Name = "Describe how this plan will be continued if events cause programs or equipment to no longer be available. For example, if equipment purchased needs repair what funding source will be used for repair or replacement? For programs that have annual subscription fees, what funds will be used to continue the program from year to year?")]
public string Sustainability { get; set; }
public bool MultipleFundingSource { get; set; }
[Required(ErrorMessage="*")]
[Display(Name = "Funding Source")]
public string FundingSource1 { get; set; }
[Required(ErrorMessage = "*")]
public string FundingSource2 { get; set; }
[Required(ErrorMessage = "*")]
public string FundingSource3 { get; set; }
[Required(ErrorMessage = "*")]
public string FundingSource4 { get; set; }
[Required(ErrorMessage = "*")]
public string FundingSource5 { get; set; }
[Required]
[Display(Name = "Total Estimated Project Costs:")]
public float TotalEstimatedProjectCosts { get; set; }
//----------------------Additional Information
[Display(Name = "Additional Comments:")]
public string AdditionalComments { get; set; }
[Display(Name = "Additional Supporting Documents:")]
public string AdditionalSupportingDocuments { get; set; }
}
The exact error is:
An error occurred while executing the command definition. See the inner exception for details.
Inner Exception:
Invalid column name 'TechnologyProjectPlanModel_Id'.
That column name isn't referenced anywhere in my code, so it must be inferring it from something.
Any ideas? Thanks!
Entity Framework relies on conventions to determine what it thinks your DB looks like. In this case, it thinks the ApprovalModel table should have a foreign key to the TechnologyProjectPlanModel table. Trimming down your entities to the relevant fields, it becomes apparent why it thinks this:
public class ApprovalModel
{
}
public class TechnologyProjectPlanModel
{
public List<ApprovalModel> Approvers { get; set; }
}
In database terms, the relationship that would most likely exist in order for there to be multiple ApprovalModel's per TechnologyProjectPlanModel would be for ApprovalModel's to have a foreign key to TechnologyProjectPlanModel's.
How does TechnologyProjectPlanModel.Approvers get set? If it doesn't have anything to do with Entity Framework and you don't want it to try populating this property via it's conventions, you can explicitly tell it not to make that assumption by telling it the property is not mapped like so:
[NotMapped]
public List<ApprovalModel> Approvers { get; set; }
If you do have this relationship, you need to give EF some more context so it doesn't make best guess assumptions. For example, if the foreign key does exist, place it in ApprovalModel along with the relevant navigation property that can further tell EF what your DB looks like:
public class ApprovalModel
{
public int TechnologyProjectPlanModelId { get; set; }
// ForeignKey attribute usually not necessary unless you need to tell EF
// about a property that doesn't follow the usual "{OtherEntityName}Id"
// naming convention.
[ForeignKey("TechnologyProjectPlanModelId")]
public TechnologyProjectPlanModel TechnologyProjectPlanModel { get; set; }
}
public class TechnologyProjectPlanModel
{
public List<ApprovalModel> Approvers { get; set; }
}
You know if you do the mapping correctly, that block of code is unnecessary because EF will retrieve results.Approvers for you.
You can use the Attribute based mapping directly on your model or you can use the Code First Configuration to map your foreign key properly.
Once you've properly mapped the foreign key, the block of code you pasted is unnecessary, EF does the load for you.

EF4 MVC3 model state validation

Using this model:
public class Cases
{
//case data model for call center
//implement lists for all related child tables too
[Key]
public int CasesID { get; set; }
public string CaseNumber { get; set; }
[Required(ErrorMessage = "Customer is Required")]
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
[MaxLength(50)]
public string UserName { get; set; } //get user name from the aspnet membership
[Required(ErrorMessage = "Case Category is Required")]
public int CaseCategoryID { get; set; }
[Required(ErrorMessage = "Technician is Required")]
public int TechnicianID { get; set; }
public virtual Technician Technicians { get; set; }
[Required(ErrorMessage = "Engine Model is Required")]
public int EngineModelID { get; set; }
public virtual EngineModel EngineModel { get; set; }
[MaxLength(50)]
public string BMSWorkorder { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Status is Required")]
public string CaseStatus { get; set; }
[MaxLength(50)]
public string OpenedBy { get; set; }
[Required(ErrorMessage = "Opened Date is Required")]
[DataType(DataType.DateTime)]
public DateTime? OpenedDate { get; set; }
[MaxLength(50)]
public string ClosedBy { get; set; }
[DataType(DataType.DateTime)]
public DateTime? ClosedDate { get; set; }
[MaxLength(50)]
[Required(ErrorMessage="Caller First Name is Required")]
public string CallerFirstName { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Caller Last Name is Required")]
public string CallerLastName { get; set; }
[MaxLength(100)]
public string AdditionalContact { get; set; }
[MaxLength(10)]
[Required(ErrorMessage = "Qualified is Required")]
public string Qualified { get; set; }
public string Description { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "ESN is Required")]
public string ESN { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "Mileage is Required")]
public string Mileage { get; set; }
[DataType(DataType.Date)]
public DateTime? DateInService { get; set; }
[MaxLength(50)]
public string ESTR { get; set; }
[MaxLength(50)]
[Required(ErrorMessage = "EDS is Required")]
public string EDS { get; set; }
[MaxLength(50)]
public string GensetSerialNumber { get; set; }
[MaxLength(50)]
public string GensetModelNumber { get; set; }
//child Case Notes records
public virtual ICollection<CaseNotes> CaseNotes { get; set; }
//child case attachment records
public virtual ICollection<Attachment> Attachments { get; set; }
//child case complaint records
public virtual ICollection<CaseComplaint> CaseComplaint { get; set; }
//tracking fields
public DateTime? CreatedOn { get; set; }
[MaxLength(50)]
public string CreatedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
[MaxLength(50)]
public string ModifiedBy { get; set; }
}
I am wondering why even though only some of the properties are marked required, the modelstate does not get set valid unless all properties have values when saving.
Am I doing something wrong?
EDIT
Here are my razor elements for the dropdownlist fields in question:
#Html.DropDownList("Qualified", String.Empty)
#Html.ValidationMessageFor(model => model.Qualified)
#Html.DropDownList("EngineModelID", String.Empty)
#Html.ValidationMessageFor(model => model.EngineModelID)
#Html.DropDownList("CaseCategoryID", String.Empty)
#Html.ValidationMessageFor(model => model.CaseCategoryID)
The EngineModelID and CaseCategoryID properties must be nullable integers on your view model if you want to allow empty values. Oooops, you are not using view models.
ASP.NET MVC automatically makes non-nullable types required. You could disable this explicitly in your Application_Start:
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
But if you want to do the things properly you should use view models.
The following is absolutely horrible:
#Html.DropDownList("CaseCategoryID", String.Empty)
I guess you have stuffed a SelectList in a ViewBag.CaseCategoryID so the CaseCategoryID does 2 things at the same time: it represents a list and a selected scalar value.
With view models you would use the strongly typed version of those helpers:
#Html.DropDownListFor(x => x.CaseCategoryID, Model.CaseCategories)
where CaseCategories will be an IEnumerable<SelectListItem> property on your view model that the controller would populate.

MVC 3 Dropdowns & Multiple Model ViewModel

I'm pretty new to MVC, but I'm trying to set up a two step user registration system. I have an register model and several other models in a viewmodel called Registration. A user will have a profile based on the register model and then they will select a Producer/Distributor/Restaurant/Importer that they are part of, or create a new one of those. My ViewModel that is returned doesn't validate or pickup the values in my dropdownlists. They populate correctly, but on the post they aren't in the vm. Below is my view/controller/and models. I've been searching the net for 2 days with no luck. Also, if you think my method of registration is wacky, let me know. Thanks!
controller:
public class RegistrationController : Controller
{
private vfContext db = new vfContext();
//
// GET: /Registration/
public ActionResult Register()
{
ViewBag.UserTypeID = new SelectList(db.UserTypes, "UserTypeID", "Name");
ViewBag.ProducerID = new SelectList(db.Producers, "ProducerID", "Name");
ViewBag.PublicationID = new SelectList(db.Publications, "PublicationID", "Name");
ViewBag.ImporterID = new SelectList(db.Importers, "ImporterID", "Name");
ViewBag.DistributorID = new SelectList(db.Distributors, "DistributorID", "Name");
ViewBag.RestaurantID = new SelectList(db.Restaurants, "RestaurantID", "Name");
RegistrationViewModel reg = new RegistrationViewModel();
ViewData.Model = reg;
return View("Registration");
}
[HttpPost]
public ActionResult Register(RegistrationViewModel vm)
{
if (ModelState.IsValid)
{
MembershipCreateStatus createStatus;
//email is userid
Membership.CreateUser(vm.Register.Email, vm.Register.Password, vm.Register.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
Profile current = Profile.GetProfile(vm.Register.Email);
current.FirstName = vm.Register.FirstName;
current.LastName = vm.Register.LastName;
current.Address1 = vm.Register.Address1;
current.Address2 = vm.Register.Address2;
current.City = vm.Register.City;
current.State = vm.Register.State;
current.Postal = vm.Register.Postal;
current.UserTypeID = vm.Register.UserTypeID;
view - i'm having a hard time copying it over, so the issue is with ddls, so here is how I have the user type id one done
#model vf2.Models.RegistrationViewModel
<div class="editor-label">
#Html.LabelFor(model => model.Register.UserTypeID, "User Type")
</div>
<div class="editor-field">
#Html.DropDownList("UserTypeID", String.Empty)
#Html.ValidationMessageFor(m => m.Register.UserTypeID)
</div>
Models:
public class RegistrationViewModel
{
public RegisterModel Register { get; set; }
public Producer Producer { get; set; }
public Distributor Distributor { get; set; }
//public Publication Publication { get; set; }
public Restaurant Restaurant { get; set; }
public Importer Importer { get; set; }
}
Here is my register model.
public class RegisterModel
{
//[Required]
//[Display(Name = "User name")]
//public string UserName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Address")]
public string Address1 { get; set; }
[Display(Name = "Address Cont.")]
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string Country { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
public int ProducerID { get; set; }
public int DistributorID { get; set; }
public int PublicationID { get; set; }
public int ImporterID { get; set; }
public int RestaurantID { get; set; }
public virtual Producer Producer{ get; set; }
public virtual Distributor Distributor { get; set; }
public virtual Publication Publication { get; set; }
public virtual Importer Importer { get; set; }
public virtual Restaurant Restaurant { get; set; }
[Required]
public int UserTypeID { get; set; }
public virtual UserType UserType { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
producer model:
public class Producer
{
public int ProducerID { get; set; }
public string Name { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string Country { get; set; }
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
public string Website { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public string UpdatedBy { get; set; }
public DateTime? UpdatedOn { get; set; }
public Boolean Active { get; set; }
public virtual ICollection<Wine> Wines { get; set; }
}
I think I figured this out by adding a the following to my viewmodel:
public IEnumerable<UserType> UserTypes { get; set; }
public IEnumerable<Producer> Producers { get; set; }
and then this to my view:
#Html.DropDownListFor(m=>m.Register.UserTypeID,new SelectList(Model.UserTypes,"UserTypeID","Name"),"Select account type")

Relationships between tables mvc3

I'm building website in MVC 3.
i am using EF code first in existing database.
my ET inside the model look like that:
public class Pages
{
[Required]
public int ID { get; set; }
public int ParentID { get; set; }
[Required]
public int PageType { get; set; }
[Required]
[DataType(DataType.Text)]
[DisplayName("כותרת")]
public string Title { get; set; }
public string SearchWords { get; set; }
public string Leng { get; set; }
public int? Sort { get; set; }
public string Modules { get; set; }
[ForeignKey("PageType")]
public virtual PagesType Type { get; set; }
public virtual IEnumerable<PagesType> Types { get; set; }
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
[ForeignKey("PageID")]
public virtual ICollection<ImagesTable> Images { get; set; }
}
public class PageContent
{
public int ID { get; set; }
public int PageID { get; set; }
public string Header { get; set; }
public string Text { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Pages> Pages { get; set; }
}
as you see in my fist table that cold Pages i have a relationship to another table that named PageContent.
in my Pages class i had this code
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
now, when i trying to add new pageContent into new page i get an error.
see this code
public ActionResult AddPage(PageModel page)
{
SystemLogic cmd = new SystemLogic();
page.Leng = "he";
Models.Pages p = new Pages();
p.ParentID = page.ParentID;
PageContent pageContent = new PageContent();
pageContent.Text = page.Content;
p.PageContent.Add(pageContent);
The error is
Object reference not set to an instance of an object.
What i did wrong?
You will get the NRE at p.PageContent.Add(pageContent); because the collection is not initialized. Initialize the collections inside the constructor of Pages class.
public class Pages
{
public Pages()
{
PageContent = List<PageContent>();
Images = List<ImagesTable>();
}
[Required]
public int ID { get; set; }
public int ParentID { get; set; }
[Required]
public int PageType { get; set; }
[Required]
[DataType(DataType.Text)]
[DisplayName("כותרת")]
public string Title { get; set; }
public string SearchWords { get; set; }
public string Leng { get; set; }
public int? Sort { get; set; }
public string Modules { get; set; }
[ForeignKey("PageType")]
public virtual PagesType Type { get; set; }
public virtual IEnumerable<PagesType> Types { get; set; }
[ForeignKey("PageID")]
public ICollection<PageContent> PageContent { get; set; }
[ForeignKey("PageID")]
public virtual ICollection<ImagesTable> Images { get; set; }
}
Or before you add objects to the collection
if (p.PageContent == null) p.PageContent = new List<PageContent>();
p.PageContent.Add(pageContent);
You should consider using proper naming conventions(eg Page instead of Pages).

Resources