Getting some input from user and insert multiple table with Entity Framework - sql

I want to add some information into my database. The question is how can I post my inputs for 3 table at the same time? My tables are below. Let me clear that.
I have teachers and working hours and working days. I want that firstly I select the teacher name from dropdownlist,then select the day from dropdownlist and write working hours for example "09:00 - 17:00".
After that I submit these information I expectation is that seeing all these information can be added into database seperately and relationally.
Sample scenario: John Reese Friday 09:00-17:00
Harold Finch Monday 11:00-15:00
I am able to pull the teacher's names from database but at the same time in the same page I want to see that day's names. After all these selecetions as I mentioned above, I wanna add all these informations.
My create controller
public ActionResult Create()
{
var myTeacherList = (from teacher in db.Teachers.ToList()
select new SelectListItem
{
Text = teacher.Firstname + teacher.Lastname,
Value = teacher.Id.ToString(),
}).ToList();
var myDayNameList = (from day in db.WeekDays.ToList()
select new SelectListItem
{
Text = day.Name,
Value = day.Id.ToString(),
}).ToList();
ViewBag.TeacherId = myTeacherList;
ViewBag.DayId = myDayNameList;
return View();
}
My Create Controller
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TeacherId, "Teacher Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m=>m.Teacher.Id,(List<SelectListItem>)ViewBag.TeacherId, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TeacherId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hours,"Working Hour", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hours, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Hours, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Teacher.cs
namespace LanguageSchool.Models
{
using System;
using System.Collections.Generic;
public partial class Teacher
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Teacher()
{
this.Appointments = new HashSet<Appointment>();
this.Classes = new HashSet<Class>();
this.Languages = new HashSet<Language>();
}
public int Id { get; set; }
public string Description { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public System.DateTime DateOfStart { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Appointment> Appointments { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Class> Classes { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Language> Languages { get; set; }
}
}
Appointment.cs
namespace LanguageSchool.Models
{
using System;
using System.Collections.Generic;
public partial class Appointment
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Appointment()
{
this.WeekDays = new HashSet<WeekDay>();
}
public int Id { get; set; }
public int TeacherId { get; set; }
public string Hours { get; set; }
public virtual Teacher Teacher { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<WeekDay> WeekDays { get; set; }
}
}
WeekDay.cs
namespace LanguageSchool.Models
{
using System;
using System.Collections.Generic;
public partial class WeekDay
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public WeekDay()
{
this.Class_WeekDay = new HashSet<Class_WeekDay>();
this.Appointments = new HashSet<Appointment>();
}
public int Id { get; set; }
public string Name { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Class_WeekDay> Class_WeekDay { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Appointment> Appointments { get; set; }
}
}

We need to make a ViewModel that contains all those properties so that the moment we do a POST request, they are all bound and we could access them for saving.
But first we need to modify your models and insert a class for the many to many table.
We need to remove Weekday from Appointments and
Appointments from Weekday.
Then replace them with AppointmentWeekday. Be sure to run Migrations/Update-Database after this first step.
public class Appointment{
...
// REMOVE public virtual ICollection<WeekDay> WeekDays { get; set; }
// Add this
public virtual ICollection<AppointmentWeekday> AppointmentWeekdays {get;set;}
}
public class Weekday{
...
// REMOVE public virtual ICollection<Appointment> Appointments { get; set; }
// Add this
public virtual List<AppointmentWeekday> AppointmentWeekdays {get;set;}
}
// Add this
public class AppointmentWeekday{
public int AppointmentId {get;set;}
[ForeignKey("AppointmentId")]
public virtual Appointment Appointment {get;set;}
public int WeekdayId {get;set;}
[ForeignKey("WeekdayId")]
public virtual Weekday Weekday {get;set;}
}
Make the View Model with the necessary properties, I named it TeacherAppointmentViewModel.
public class TeacherAppointmentViewModel{
public int TeacherId {get;set;}
public int DayId {get;set;}
public string Hours {get;set;}
}
Instantiate this in your controller and pass it to the view.
public ActionResult Create()
{
var myTeacherList = (from teacher in db.Teachers.ToList()
select new SelectListItem
{
Text = teacher.Firstname + teacher.Lastname,
Value = teacher.Id.ToString(),
}).ToList();
var myDayNameList = (from day in db.WeekDays.ToList()
select new SelectListItem
{
Text = day.Name,
Value = day.Id.ToString(),
}).ToList();
ViewBag.TeacherId = myTeacherList;
ViewBag.DayId = myDayNameList;
// instantiate
TeacherAppointmentViewModel tvm = new TeacherAppointmentViewModel();
// pass to the view
return View(tvm);
}
Make your view use TeacherAppointmentViewModel.
#model TeacherAppointmentViewModel
Edit view, use the code below.
<div class="form-horizontal">
<h4>Appointment</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TeacherId, "Teacher Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m=>m.TeacherId,(List<SelectListItem>)ViewBag.TeacherId, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TeacherId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WeekdayId, "Day", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m=>m.WeekdayId,(List<SelectListItem>)ViewBag.WeekdayId, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.WeekdayId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hours,"Working Hour", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hours, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Hours, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
Use controller action below, we need to assign the properties to Appointment and AppointmentWeekday then add to the db;
[HttpPost]
public ActionResult Create(TeacherAppointmentViewModel tvm){
// create appointment
Appointment a = new Appointment();
// assign teacher id and hours from viewmodel
a.TeacherId = tvm.TeacherId;
a.Hours = tvm.Hours;
// save appointment
db.Appointments.Add(a);
db.SaveChanges();
// create appointmentweekday
AppointmentWeekday aw = new AppointmentWeekday();
// assign properties
// since we've saved the appointment, we could use a.AppointmentId
aw.WeekdayId = tvm.WeekdayId;
aw.AppointmentId = a.AppointmentId; // appointment from earlier
// save appointmentweekday
db.AppointmentWeekdays.Add(aw);
db.SaveChanges();
}

Related

How to post HttpPostedFileBase with Model data from MVC

How to upload file with HttpPostedFileBase with 3 other Model data
and save it to database.When i try to save data employee model value
become null and give object reference error.I have a Create view link
for New employee on Get Page. I am getting object refrence error when
try to save.
EmployeeModelClass.cs
public class EmployeeViewModel
{
public Employee Employee { get; set; }
public HttpPostedFileBase File { get; set; }
public List<Employee> EmployeeList { get; set; }
public IEnumerable<Region> Regions { get;set; }
public IEnumerable<City> Cities { get; set; }
}
EmployeClass
public class Employee
{
[Key]
public int EmployeeId { get; set; }
public string Name { get; set; }
[DataType(DataType.DateTime)]
public DateTime? BirthDate { get; set; }
[Display(Name = "Region")]
public int RegionId { get; set; }
public City City { get; set; }
[Display(Name = "City")]
public int CityId { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.Password)]
public string Confirm Password { get; set; }
public int ImageSize { get; set; }
public string FileName { get; set; }
public byte[] ImageData { get; set; }
}
Get Request for Create.And here i am redirect from Get.chtml view.
[HttpGet]
public ActionResult Create()
{
var viewmodel = new EmployeeViewModel
{
Regions = _context.Regions.ToList(),
Cities = _context.Cities.ToList(),
};
return View("Create", viewmodel);
}
Post Request for Create .Here my employee model value becoming null and on submit give object refrence null error.
[HttpPost]
public ActionResult Create(HttpPostedFileBase file,Employee emp)
{
}
Create.chtml
#model EmployeeManagement.ViewModel.EmployeeViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (#Html.BeginForm("Create", "Employee", FormMethod.Post, new {
enctype = "multipart/form-data" }))
{
<div class = "form-group">
#Html.LabelFor(m => m.Employee.Name)
#Html.TextBoxFor(m => m.Employee.Name, new { #class = "form-control"
})
</div>
<div class = "form-group">
#Html.LabelFor(m => m.Employee.BirthDate)
#Html.TextBoxFor(m => m.Employee.BirthDate, new { #class = "form-
control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Employee.RegionId)
#Html.DropDownListFor(m => m.Employee.RegionId, new
SelectList(Model.Regions, "RegionId", "RegionName"), "Please Select
Region", new { #onchange = "BindCity()", #class = "form-control" })
#Html.ValidationMessageFor(m => m.Employee.RegionId)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Employee.CityId)
#Html.DropDownListFor(m => m.Employee.CityId, new
SelectList(Model.Cities, "CityId", "CityName"), "Please Select
City", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Employee.CityId)
</div>
<div class="form-group">
#Html.LabelFor(m => m.Employee.Password)
#Html.PasswordFor(m => m.Employee.Password, new { #class = "form-
control" })
</div>
<div class="form-group">
#Html.LabelFor(m => m.Employee.ConfirmPassword)
#Html.PasswordFor(m => m.Employee.ConfirmPassword, new { #class =
"form-control" })
</div>
<div>
#Html.TextBoxFor(m=>m.File, new { type = "file",name="File" })
#Html.ValidationMessageFor(m=>m.File.FileName)
</div>
<p><button type="submit" class="btn btn-primary">Save</button></p>
}
Please someone help how to upload image with model data at
post.
The problem in your Post Create method you are expecting Employee object but you are binding EmployeeViewModel with view so use below line it's resolve your issue.
public ActionResult Create(HttpPostedFileBase file,EmployeeViewModel emp)

Get the Id of elected Item fro dropdownlistfor Using Enum in asp.net mvc 4

i'm trying to get the Id of a DropdownList into a model using Enum but I always get null inside the variable of the Model. Hier ist my Code.
Model:
public partial class Vehicule
{
public int vehiculeID { get; set; }
public Nullable<int> paidTextID { get; set; }
}
the Enum Class
public class EnumClass
{
public enum Paid
{
Yes = 1 ,
No = 2 ,
NotComplete= 3,
}
}
and the View
<div class="form-group">
#Html.LabelFor(model => model.paid, new { #class = "control-label col-md-2" })*
<div class="col-md-10">
#Html.DropDownListFor(model => model.paidTextID, Enum.GetValues(typeof(EnumClass.Paid)).Cast<EnumClass.Paid>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }), new { style = "width: 500px" })
#Html.ValidationMessageFor(model => model.paid)
</div>
</div>
The List is populated but when I select I till have null inside the paidTextID.
Please Help
Thx

ASP.NET MVC - Object reference not set to an instance of an object in DropDownList

I have a model Class
public partial class FEES
{
public FEES()
{
}
public long FEE_ID { get; set; }
public decimal AMOUNT { get; set; }
public int CURRENCY_ID { get; set; }
public string NAME { get; set; }
public virtual CURRENCIES CURRENCIES { get; set; }
}
ViewModel
public class FeesViewModel
{
public SelectList CurrenciesList { get; set; }
public FeesViewModelInput input { get; set; }
public class FeesViewModelInput
{
[HiddenInput]
public long FEE_ID { get; set; }
[Display(Name = "Amount")]
[Required(ErrorMessage = "Fee Amount Is Required!")]
[RegularExpression(#"^[0-9,.]+$", ErrorMessage = "Please enter proper currency format e.g. 2,500")]
public decimal AMOUNT { get; set; }
[Display(Name = "Currency")]
[Required(ErrorMessage = "Currency Is Required!")]
public int CURRENCY_ID { get; set; }
[Required(ErrorMessage = "Fee Name Is Required!")]
[Display(Name = "Fee Name")]
public string NAME { get; set; }
}
}
Small service for the ViewModel
public void createFees(FEES fee, FeesViewModel viewModel)
{
fee.FEE_ID = viewModel.input.FEE_ID;
fee.CURRENCY_ID = viewModel.input.CURRENCY_ID;
fee.NAME = viewModel.input.NAME.Trim();
}
I call the service and the ViewModel in my controller.
Controller
public ActionResult Create()
{
FeesViewModel fees = new FeesViewModel();
fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
fees.FeeTypesList = new SelectList(_feetypesService.GetFeeTypes().Where(c => c.ACTION_STATUS != 2), "FEE_TYPE_ID", "FEE_TYPE_NAME");
return View();
}
[HttpPost]
public ActionResult Create(FeesViewModel fees)
{
try
{
if (ModelState.IsValid)
{
//check if values is duplicate
if (_feesService.GetFees().Where(c => c.ACTION_STATUS != 2).Any(c => c.NAME.ToLower().Trim() == fees.input.NAME.ToLower().Trim()))
{
this.AddNotification("Fee Name already exist.<br/> Kindly verify the data.", NotificationType.ERROR);
}
else
{
var fee = new BPP.CCSP.Admin.Web.BPPCCSPAdminFeesService.FEES();
var helper = new FeesService();
helper.createFees(fee, fees);
_feesService.AddFee(fee);
var notif = new UINotificationViewModel()
{
notif_message = "Record saved successfully",
notif_type = NotificationType.SUCCESS,
};
TempData["notif"] = notif;
return RedirectToAction("Index");
}
}
}
catch (Exception e)
{
this.AddNotification("Fees cannot be added.<br/> Kindly verify the data.", NotificationType.ERROR);
}
fees.CurrenciesList = new SelectList(_currenciesService.GetCurrencies().Where(c => c.ACTION_STATUS != 2), "CURRENCY_ID", "CURRENCY_NAME");
return View(fees);
}
And the View
#model BPP.CCSP.Admin.Web.ViewModels.FeesViewModel
#{
//ViewBag.Title = "Create";
}
<div class=" box box-body box-primary">
#using (Html.BeginForm("Create", "Fees", FormMethod.Post, new { #class = "form-horizontal", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, null, new { #class = "text-danger" })
#*#Html.HiddenFor(model => model.faculty_activation_date, new { #Value = System.DateTime.Now })*#
<div class="row .col">
<div style="margin-top:20px" class="mainbox col-md-12 col-md-offset-0 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Create Fee</div>
</div>
<div class="panel-body">
<div class="col-md-6">
<div>
#Html.LabelFor(model => model.input.NAME, "Fee Name")
#Html.TextBoxFor(model => model.input.NAME, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.input.NAME), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.input.NAME, null, new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.input.AMOUNT, "Amount")
#Html.TextBoxFor(model => model.input.AMOUNT, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.input.AMOUNT), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.input.AMOUNT, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-6">
<div>
#Html.LabelFor(model => model.input.CURRENCY_ID, "Currency")
#*#Html.DropDownList("CURRENCY_ID", (IEnumerable<SelectListItem>)ViewBag.name, "Please Select a Currency", new { #class = "form-control", #style = "border-radius:3px;" })*#
#Html.DropDownListFor(x => x.input.CURRENCY_ID, Model.CurrenciesList, "Please Select a Currency", new { #class = "form-control", #style = "border-radius:3px;" })
#Html.ValidationMessageFor(model => model.input.CURRENCY_ID, null, new { #class = "text-danger" })
</div>
<div>
#Html.LabelFor(model => model.input.FEE_TYPE_ID, "Fee Type")
#Html.DropDownListFor(model => model.input.FEE_TYPE_ID, Model.FeeTypesList, "Please Select a Fee Type", new { #class = "form-control", #style = "border-radius:3px;" })
#Html.ValidationMessageFor(model => model.input.FEE_TYPE_ID, null, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="panel-title">
<div class="form-actions no-color">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
</div>
}
When I clicked on the View (Create), I got this error
The CurrencyID is a DropDownList coming from CURRENCIES model class.
I have these questions:
Why am I getting this error and how do I resolve it.
How do I do ViewModel without mapping.?
Why am I getting this error and how do I resolve it.
Because the Model is not set in your view. It is null.
When the users visit the Create page, you need to make sure to present them with options in the dropdown. Therefore, you need to make sure you pass the model into the view during GET.
public ActionResult Create()
{
// your code and pass fees to your view.
return View(fees);
}
How do I do ViewModel without mapping. Any example please.
You can use AutoMapper NuGet package to do the mapping.

MVC - Foreign Key Error because of ViewModel?

I am Creating View Model of Employee Class and strongly typed my Create View with the EmployeeViewModel. In future, I will add many classes in my View Model. But the problem is I am getting Gender Foreign Key Error. May be I am binding wrong values in Create Controller. Below is my code:
Create Controllers:
public ActionResult Create()
{
ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeeViewModel employeeModel)
{
if (ModelState.IsValid)
{
db.Employees.Add(employeeModel.Employee);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.GenderId = new SelectList(db.Genders, "Id", "Name", employeeModel.Employee.GenderId);
return View(employeeModel);
}
Create View:
#model WebApplication2.EmployeeViewModel
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Employee.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee.GenderId, "GenderId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GenderId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Employee.GenderId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
Models:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public byte GenderId { get; set; }
public Gender Gender { get; set; }
}
public class Gender {
public byte Id { get; set; }
public string Name { get; set; }
}
View Model:
public class EmployeeViewModel
{
public Employee Employee { get; set; }
}

System.ArgumentNullException: Value cannot be null. Parameter name: items

I receive the error System.ArgumentNullException: Value cannot be null. Parameter name: items on this line:
#Html.DropDownList("empnames", new SelectList(ViewBag.empnames), "Select");
I want to get the corresponding Emp_id from the selected Emp_Name and want to update my table Enq_Submission.
My Model,Controller and Views are as follows:
Model:
namespace MvcConQuery.Models
{
[Table("Enq_Submission")]
public class EnquiryModel
{
private ConQueryDataClassesDataContext dc = new ConQueryDataClassesDataContext();
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Int32 Enq_id { get; set; }
[Required]
[Display(Name="Name")]
public string CustomerName { get; set; }
[ReadOnly(true)]
public string Date
{
get
{
DateTime Date = DateTime.Now;
return Date.ToString("yyyy-MM-dd"); ;
}
set{}
}
[Required]
[Display(Name = "Region")]
public string Region { get; set; }
[Required]
[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Entered phone number format is not valid.")]
[Display(Name = "Phone number")]
public string Ph_No { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email_id")]
public string Email_id { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
[Required]
[Display(Name = "Query")]
public string Query { get; set; }
public string Referral { get; set; }
public string Feedback { get; set; }
public string Status { get; set; }
public Int32? Emp_id { get; set; }
public string FollowUpDate { get; set; }
public List<EmployeeModel> Employees { get; set; }
}}
namespace MvcConQuery.Models
{
[Table("Employee_Details")]
public class EmployeeModel
{
[Key,Column(Order=0)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
//[ForeignKey("EnquiryModel")]
public Int32 Emp_id { get; set; }
public string Emp_Name{ get; set; }
//[Key,Column(Order=1)]
public string Region { get; set; }
//[ForeignKey("Region")]
public string Emp_PhNo { get; set; }
public string Emp_Address { get; set; }
public List<EnquiryModel> Enquires { get; set; }
}
}
Controller:
public ActionResult Edit(int id)
{
EnquiryModel enquirymodel = db.Enquires.Find(id);
if (enquirymodel == null)
{
return HttpNotFound();
}
var rgn=enquirymodel.Region;
var empnames = (from ename in dc.GetTable<Employee_Detail>() where ename.Region ==rgn select ename.Emp_Name).ToList();
ViewBag.empnames = empnames;
return View(enquirymodel);
}
[HttpPost]
public ActionResult Edit(EnquiryModel enquirymodel,string empnames)
{
if (ModelState.IsValid)
{
var empid = (from eid in dc.GetTable<Employee_Detail>() where eid.Emp_Name == empnames select eid.Emp_id).First();
enquirymodel.Emp_id = empid;
db.SaveChanges();
}
return View(enquirymodel);
}
View:
#model MvcConQuery.Models.EnquiryModel
#{
ViewBag.Title = "Edit";
}
<style>
.myClass label{
font-weight:bold;
}
</style>
<h2>Allocate Employee</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>EnquiryModel</legend>
#Html.HiddenFor(model => model.Enq_id)
#Html.HiddenFor(model => model.CustomerName)
#Html.HiddenFor(model => model.Date)
#Html.HiddenFor(model => model.Region)
#Html.HiddenFor(model => model.Ph_No)
#Html.HiddenFor(model => model.Email_id)
#Html.HiddenFor(model => model.Address)
#Html.HiddenFor(model => model.Query)
#Html.HiddenFor(model => model.Referral)
#Html.HiddenFor(model => model.Feedback)
#Html.HiddenFor(model => model.Status)
#Html.HiddenFor(model => model.FollowUpDate)
#Html.HiddenFor(Model => Model.Emp_id);
<div class="editor-label">
#Html.LabelFor(model => model.CustomerName, new { #class = "label" })
</div>
#Html.DisplayFor(model => model.CustomerName)
<div class="editor-label">
#Html.LabelFor(model => model.Region, new { #class = "label" })
</div>
#Html.DisplayFor(model => model.Region)
<div class="editor-label">
#Html.LabelFor(model => model.Ph_No, new { #class = "label" })
</div>
#Html.DisplayFor(model => model.Ph_No)
<div class="editor-label">
#Html.LabelFor(model => model.Email_id, new { #class = "label" })
</div>
#Html.DisplayFor(model => model.Email_id)
<div class="editor-label">
#Html.LabelFor(model => model.Address, new { #class = "label" })
</div>
#Html.DisplayFor(model => model.Address)<div class="editor-label">
#Html.LabelFor(model => model.Query, new { #class = "label" })
</div>
#Html.DisplayFor(model => model.Query)
#Html.Label("Select Employee", new { #class = "label" })
#Html.DropDownList("empnames", new SelectList(ViewBag.empnames), "Select");
<p>
<input type="submit" value="Allocate" name="Submit"/>
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Can anyone help me in how I can solve this problem, please?
I guess you are in the Edit view.
In contrary to the first Edit action, the second doesn't have this line:
var empnames = (from ename in dc.GetTable<Employee_Detail>() where ename.Region ==rgn select ename.Emp_Name).ToList();
ViewBag.empnames = empnames;
Can you check if it helps adding that?
EDIT:
I don't think you understand the internal mechanism of MVC. When you return View(...) it renders the view with the same name as the method (Edit in your case). Since both render Edit it expects the empnames ViewBag value to be filled.
You can also try to return this in the second Edit:
ViewBag.empnames = new List<Employee_Detail>();
The Problem was both 'Edit' expects the empnames ViewBag value to be filled.
Then the reason behind Not updating the table was missing a line of code in the controller, that is:
db.Entry(enquirymodel).State = EntityState.Modified;
[HttpPost]
public ActionResult Edit(EnquiryModel enquirymodel,string empnames)
{
if (ModelState.IsValid)
{
var rgn = enquirymodel.Region;
var empnamess = (from ename in dc.GetTable<Employee_Detail>() where ename.Region == rgn select ename.Emp_Name).ToList();
ViewBag.empnames = empnamess;
var empid = (from eid in dc.GetTable<Employee_Detail>() where eid.Emp_Name == empnames select eid.Emp_id).First();
db.Entry(enquirymodel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(enquirymodel);
}