How to combine two entities in one view? - asp.net-mvc-4

I need to display the records of the student which is the Student Attempts.
It should look something like this.
https://www.dropbox.com/s/pmazbug2j8xwehe/Example.PNG (Click for image)
But this is the Question page which shows all the correct answers. For the Student Attempts page should be exactly like that only the answers/options are replaced by the answers they attempted so when it is correct, the word will be in green and the wrong ones will be in red.
For this to happen I have to retrieve 2 data from two different entities.
Below is the IQuestion table and QuestionContent is the attribute that holds the model answers and the StudentAttempts table and Answer is the attribute that holds the answers attempted by the students.
https://www.dropbox.com/s/f92f8zvk9qn1n8p/DB%20Tables.PNG (Click for image)
How do I combine those two attributes to display in a view?
StudentAttemptsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using iStellarMobile.Models;
namespace iStellarMobile.Controllers
{
public class StudentAttemptsController : Controller
{
private istellarEntities db = new istellarEntities();
//
// GET: /StudentAttempts/
public ActionResult Index(int id)
{
var studentattempts = db.StudentAttempts.Include(s => s.activity).Include(s => s.task).Include(s => s.UserInfo).Where(s => s.StudentID == id);
return View(studentattempts.ToList());
}
//
// GET: /StudentAttempts/Details/5
public ActionResult Details(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
return View(studentattempt);
}
//
// GET: /StudentAttempts/Create
public ActionResult Create()
{
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName");
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName");
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName");
return View();
}
//
// POST: /StudentAttempts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StudentAttempt studentattempt)
{
if (ModelState.IsValid)
{
db.StudentAttempts.Add(studentattempt);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// GET: /StudentAttempts/Edit/5
public ActionResult Edit(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// POST: /StudentAttempts/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(StudentAttempt studentattempt)
{
if (ModelState.IsValid)
{
db.Entry(studentattempt).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// GET: /StudentAttempts/Delete/5
public ActionResult Delete(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
return View(studentattempt);
}
//
// POST: /StudentAttempts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
db.StudentAttempts.Remove(studentattempt);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
IQuestion.cs (Models)
namespace iStellarMobile.Models
{
using System;
using System.Collections.Generic;
public partial class IQuestion
{
public int ID { get; set; }
public Nullable<int> ActivityID { get; set; }
public Nullable<int> TaskID { get; set; }
public Nullable<int> CategoriesID { get; set; }
public Nullable<bool> Sentence { get; set; }
public string QuestionContent { get; set; }
public string ImageURL { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
public string UpdateBy { get; set; }
public Nullable<System.DateTime> UpdateOn { get; set; }
public Nullable<int> SchoolID { get; set; }
public Nullable<int> DLevel { get; set; }
public Nullable<int> TagID { get; set; }
public virtual ActivityTask ActivityTask { get; set; }
public virtual Category Category { get; set; }
public virtual School School { get; set; }
public virtual Tag Tag { get; set; }
}
}
StudentAttempts.cs (Models)
namespace iStellarMobile.Models
{
using System;
using System.Collections.Generic;
public partial class StudentAttempt
{
public int ID { get; set; }
public Nullable<int> ActivityID { get; set; }
public Nullable<int> TaskID { get; set; }
public Nullable<int> StudentID { get; set; }
public string Answer { get; set; }
public string Score { get; set; }
public Nullable<int> Attempts { get; set; }
public string AttemptDate { get; set; }
public string CorrectAnswer { get; set; }
public virtual activity activity { get; set; }
public virtual task task { get; set; }
public virtual UserInfo UserInfo { get; set; }
}
}
Details.cshtml (StudentAttempts view)
<fieldset>
<legend>Classes</legend>
<div class="editor-label">
<h2> #Html.LabelFor(model => model.activity.ActivityName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.activity.ActivityName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.task.TaskName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.task.TaskName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.UserInfo.UserName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.UserInfo.UserName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Answer) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Answer)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Score) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Score)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Attempts) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Attempts)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.AttemptDate) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.AttemptDate)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.CorrectAnswer) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.CorrectAnswer)
</div>
</fieldset>
<br />
<p>
#Html.ActionLink("Edit", "/Edit/2",null, new { id=Model.ID, #class="classname" })
<span> </span>
#Html.ActionLink("Back", "/Index", null, new { #class="classname" })
</p>

You could just make a new class type (something like "StudentAttempsVM") that has a property for each of the classes you need (Details and Attempts). Then consolidate your Controller methods to build this object and pass it to your view.

Related

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

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();
}

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)

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);
}

how create dropdown in mvc 4

i have these models:
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "Ürün Adı")]
public string Name { get; set; }
[Required]
[Display(Name = "Açıklama")]
public string Description { get; set; }
[Required]
[Display(Name = "Fiyat")]
public decimal Price { get; set; }
[Required]
[Display(Name = "İndirim")]
public decimal Discount { get; set; }
[Required]
[Display(Name = "İndirim Geçerli Mi?")]
public bool IsDiscountActive { get; set; }
[Required]
[Display(Name="Ürün Var Mı?")]
public bool IsAvailable { get; set; }
[Required]
[Display(Name="Kategori")]
public Category Category { get; set; }
[Display(Name="Resim")]
public Image Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public DateTime ChangedOn { get; set; }
[Required]
public UserProfile CreatedBy { get; set; }
public UserProfile ChangedBy { get; set; }
public IEnumerable<SelectListItem> Categories
{
get
{
return new OnlineShoppingContext().Categories.OrderBy(c=>c.Name).ToList()
.Select(e => new SelectListItem { Text = e.Name, Value = e.Id.ToString() });
}
}
}
[Table("Category")]
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "Kategori Adı")]
public string Name { get; set; }
[Display(Name = "Açıklama")]
public string Description { get; set; }
[Display(Name = "Resim")]
public Image Image { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreatedOn { get; set; }
public DateTime ChangedOn { get; set; }
public UserProfile CreatedBy { get; set; }
public UserProfile ChangedBy { get; set; }
public List<Product> Products { get; set; }
}
My category controller
[Authorize(Roles = "Admin")]
public class CategoryController : Controller
{
private OnlineShoppingContext db = new OnlineShoppingContext();
//
// GET: /Category/
public ActionResult Index()
{
return View(db.Categories.ToList());
}
//
// GET: /Category/Details/5
public ActionResult Details(int id = 0)
{
Category category = db.Categories.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
//
// GET: /Category/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Category/Create
[HttpPost]
public ActionResult Create(Category category, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
string pic = Guid.NewGuid().ToString();
string path = Path.Combine(Server.MapPath("~/Content/images/"), pic + Path.GetExtension(file.FileName));
file.SaveAs(path);
Image i = new Image();
i.Path = path;
i.CreatedBy = db.UserProfiles.Where(u => u.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
category.Image = i;
}
category.CreatedBy = db.UserProfiles.Where(u => u.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
//
// GET: /Category/Edit/5
public ActionResult Edit(int id = 0)
{
Category category = db.Categories.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
//
// POST: /Category/Edit/5
[HttpPost]
public ActionResult Edit(Category category)
{
if (ModelState.IsValid)
{
db.Entry(category).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
//
// GET: /Category/Delete/5
public ActionResult Delete(int id = 0)
{
Category category = db.Categories.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
//
// POST: /Category/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Category category = db.Categories.Find(id);
db.Categories.Remove(category);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
create.cshtml
#model OnlineShopping.Models.Product
#{
var db = new OnlineShopping.Models.OnlineShoppingContext();
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
// Error Model is null
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Categories, "Value", "Text"))
#Html.ValidationMessageFor(model => model.Category)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Discount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Discount)
#Html.ValidationMessageFor(model => model.Discount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsDiscountActive)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IsDiscountActive)
#Html.ValidationMessageFor(model => model.IsDiscountActive)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsAvailable)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IsAvailable)
#Html.ValidationMessageFor(model => model.IsAvailable)
</div>
<div class="editor-field">
<input type="file" name="file" id="file" />
</div>
<p>
<input type="submit" value="#Translations.Common.Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink(Translations.Common.BackToList, "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
On create.cshtml page i got this error
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Line 19:
Line 20:
Line 21: #Html.DropDownListFor(model => model.Category, new SelectList(Model.Categories, "Value", "Text"))
Line 22: #Html.ValidationMessageFor(model => model.Category)
Line 23:
In GET your Model is null, so Model.Categories crashes. Try the following:
//
// GET: /Category/Create
public ActionResult Create()
{
var model = new OnlineShopping.Models.Product();
return View(model);
}
Your create view expected you to pass in a model, then in your view, it will look for model's value to generate dropdown list for you. As you haven't pass a model in so you get that object null reference exception.
Also, when you pass a model in, make sure it contains all the data you need to populate the dropdown list.

System.NullReferenceException: Object reference not set to an instance of an object. bootstrap dropdownlist

Model
public class Employee
{
public int EmployeeID { get; set; }
public string Title { get; set; }
[Required(ErrorMessage = "Please enter first name.")]
[StringLength(500)]
public string FirstName { get; set; }
public string MI { get; set; }
[Required(ErrorMessage = "Please enter last name.")]
[StringLength(500)]
public string LastName { get; set; }
public string Gender { get; set; }
[Required(ErrorMessage = "Please select date of birth.")]
public Nullable<System.DateTime> DateOfBirth { get; set; }
[Required(ErrorMessage = "Please enter email.")]
[StringLength(500)]
[EmailAddress]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter street.")]
[StringLength(500)]
public string Street { get; set; }
[Required(ErrorMessage = "Please enter state.")]
[StringLength(50)]
public string State { get; set; }
[Required(ErrorMessage = "Please enter city.")]
[StringLength(50)]
public string City { get; set; }
[Required(ErrorMessage = "Please enter country.")]
[StringLength(50)]
public string Country { get; set; }
[Required(ErrorMessage = "Please enter post code.")]
[StringLength(6)]
public string PostCode { get; set; }
[Required(ErrorMessage = "Please enter home phone.")]
public string HomePhone { get; set; }
[Required(ErrorMessage = "Please enter mobile phone.")]
public string MobilePhone { get; set; }
}
Controller Method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(employee);
}
View
#model EmployeeManagementSystem.Models.Employee
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<div class="row-fluid">
<div class="span12">
#using (Html.Bootstrap().Begin(new Form().Id("CreateEmployee").Type(FormType.Inline)))
{
#Html.AntiForgeryToken()
<div class="span12">
<fieldset>
<div class="span4">
<legend>Employee Info</legend>
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.FirstName).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.LastName).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().DropDownListFor(m => m.Gender, ViewBag.GenderList as SelectList).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().Class("input-append date").TextBoxFor(x => x.DateOfBirth).Size(InputSize.BlockLevel).AppendIcon(Icons.calendar).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Email).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
</div>
<div class="span8 ">
<legend>Contact Details</legend>
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Street).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
<div class="span6" style="margin-left:0px">
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.City).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.State).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.HomePhone).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block).HtmlAttributes(new Dictionary<string, Object> { { "data-mask", "(99999)(999999)" } })
</div>
<div class="span6">
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.PostCode).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Country).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block)
#Html.Bootstrap().ControlGroup().TextBoxFor(x => x.MobilePhone).Size(InputSize.BlockLevel).ShowValidationMessage(true, HelpTextStyle.Block).HtmlAttributes(new Dictionary<string, Object> { { "data-mask", "+99 (9999)(999999)" } })
</div>
</div>
</fieldset>
#Html.Bootstrap().SubmitButton().Style(ButtonStyle.Primary)
#Html.Bootstrap().ActionLinkButton("Cancel", "Index").Style(ButtonStyle.Default)
</div>
}
</div>
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
//$('[rel=tooltip]').tooltip();
$('#CreateEmployee .input-append.date').datepicker({
startView: 2,
autoclose: true
});
});
</script>
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/BootstrapFormHelpersJS")
#Styles.Render("~/Content/BootstrapFormHelpersCSS")
}
Hi this is get method of my controller.
[HttpGet]
public ActionResult Create()
{
List<string> genders = new List<string>();
genders.Add("--Select--");
genders.Add("Male");
genders.Add("Female");
genders.Add("Not Defind");
ViewBag.GenderList = new SelectList(genders, "--Select--");
return View();
}