how create dropdown in mvc 4 - asp.net-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.

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)

How to combine two entities in one view?

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.

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

Model is null after submit

I wonder why the ContactModel in ContactController is not filled with the values provided in the form. Where has my head exploded?
Code as is:
HomeController (where the contact form is)
public class HomeController : Controller
{
public ActionResult Index()
{
var viewModel = new HomeViewModel();
return View(viewModel);
}
}
ViewModel for Home
public class HomeViewModel
{
public ContactModel ContactModel { get; set; }
}
ContactModel to hold the values
public class ContactModel
{
[Required(ErrorMessage = "Required")]
public String Name { get; set; }
[EmailAddress]
[Required(ErrorMessage = "Required")]
public String Email { get; set; }
[Required(ErrorMessage = "Required")]
public String Message { get; set; }
}
Index View for HomeController
#model MyNameSpace.ViewModels.HomeViewModel
#using (Html.BeginForm("Send", "Contact", FormMethod.Post))
{
<div class="form-group">
#Html.LabelFor(model => model.ContactModel.Name, "Name", new { #class = "sr-only" })
#Html.TextBoxFor(model => model.ContactModel.Name, new { #class = "form-control", #placeholder = "Name" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactModel.Email, "E-mail", new { #class = "sr-only" })
#Html.TextBoxFor(model => model.ContactModel.Email, new { #class = "form-control", #placeholder = "E-mail" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContactModel.Email, "Message", new { #class = "sr-only" })
#Html.TextAreaFor(model => model.ContactModel.Message, new { #class = "form-control", #placeholder = "Message" })
</div>
<p><button type="submit" class="btn btn-default">Send</button></p>
}
ContactController Send
public class ContactController : Controller
{
[HttpPost]
public ActionResult Send(ContactModel model)
{
if (ModelState.IsValid)
{
// ModelState is not valid - but why!?
return RedirectToAction("Index", "Success");
}
return RedirectToAction("Index", "Error");
}
}
For some reason on my form submit, the model provided in ContactController.Send(ContactModel model) has all null values - where is the link broken?
Your POST action should take the view model as parameter instead of your domain model:
[HttpPost]
public ActionResult Send(HomeViewModel model)
The reason for that is pretty simple - it's the way the default model binder works. Your input fields in the view are all prefixed with ContactModel.
Alternatively you could use the Bind attribute and explicitly specify that:
[HttpPost]
public ActionResult Send([Bind(Prefix = "ContactModel")] ContactModel model)

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