ASP.NET MVC date not saving when posting - c#

Having an issue with some dates on a form not posting back. I am entering a date into the fields, but the app seems to be posting a blank DateTime back - "01/01/0001 00:00:00"
This is the form:
This is what is being posted:
This is the controller:
public ActionResult Add()
{
var skillsetIDs = db.SkillSets.Select(x => x.IDSkillset).Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in skillsetIDs)
{
SelectListItem s = new SelectListItem();
int catID = db.SkillSets.Where(c => c.IDSkillset == t).Select(x => x.IDCategory).Single();
string product = db.SkillSets.Where(c => c.IDSkillset == t).Select(x => x.Product + " V. " + x.P_Version).Single();
string category = db.Categories.Where(c => c.IDCategory == catID).Select(x => x.Category + ": " + x.C_Role + " - ").Single();
s.Text = category + product;
s.Value = t.ToString();
items.Add(s);
}
ViewBag.Campaign = items;
var personIDs = db.Personnel.Select(x => x.IDPerson).Distinct();
List<SelectListItem> items2 = new List<SelectListItem>();
foreach (var t in personIDs)
{
SelectListItem s = new SelectListItem();
s.Text = db.Personnel.Where(c => c.IDPerson == t).Select(x => x.Fornames + " " + x.Surname).Single();
s.Value = t.ToString();
items2.Add(s);
}
ViewBag.Person = items2;
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(Models.PersonSkillsModel model)
{
try
{
if (ModelState.IsValid)
{
db.PersonSkills.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
The view:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>PersonSkillsModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.IDSkillSet, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.IDPerson, (IEnumerable<SelectListItem>)ViewBag.Person)
#Html.ValidationMessageFor(model => model.IDSkillSet, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IDSkillSet, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.IDSkillSet, (IEnumerable<SelectListItem>)ViewBag.Campaign)
#Html.ValidationMessageFor(model => model.IDSkillSet, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Score, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Score, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Score, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ScoreDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ScoreDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ScoreDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TargetScore, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TargetScore, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TargetScore, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TargetDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TargetDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TargetDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RefresherDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RefresherDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RefresherDate, "", 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>
}
The model:
[Table("PersonSkills")]
public class PersonSkillsModel
{
[Key]
public int PersonSkillsID { get; set; }
public int IDPerson { get; set; }
public int IDSkillSet { get; set; }
public int Score { get; set; }
public DateTime ScoreDate { get; set; }
public int TargetScore { get; set; }
public DateTime TargetDate { get; set; }
public DateTime RefresherDate { get; set; }
}

Could you add Data Annotation and debug again?
[DataType(DataType.Date)]
public DateTime ScoreDate { get; set; }

I was facing similar issue few days back.. see if below one works..
decorate datetime properties with following attibute
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MMMMM-dd}")]

Related

when clicking on create new hole Would like to be able to select a courseId

I am trying to create a golf score app. I have created the database that has the following tables Round, Course and Hole.
The hole table has a foreign key to the courseId as when I create each hole I want to link it to a course.
When clicking on the create new I would like to have a dropdown list to select the courseId from when inputting all the hole details.
But when I click on the create new I get the following error in the Hole view model.
System.ArguementNullException: Value can not be Null. Parameter name items. in my Create action code within the HoleViewModelController.
This is my HoleViewModel code
public class HoleViewModel
{
[Key]
public int HoleId { get; set; }
public int HoleNumber { get; set; }
public int Par { get; set; }
public int Length { get; set; }
public int StrokeIndex { get; set; }
[ForeignKey("Course")]
public int? CourseId { get; set; }
public IEnumerable<SelectListItem> CourseNamesDropdownList { get; set; }
public virtual CourseViewModel Course { get; set; }
}
}
This is my CourseViewModel code
public class CourseViewModel
{
[Key]
public int CourseId { get; set; }
public string CourseName { get; set; }
This is my HoleViewModelController Create action
public ActionResult Create()
{
ViewBag.CourseId = new SelectList(db.CourseViewModels, "CourseId", "CourseName");
return View();
}
This is my MVC Create view
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HoleViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.HoleNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HoleNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HoleNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Par, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Par, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Par, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Length, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Length, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Length, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StrokeIndex, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StrokeIndex, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StrokeIndex, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CourseId, "CourseId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Course.CourseId, Model.CourseNamesDropdownList, "Please select from List", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CourseId, "", 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>
Ok so i resolved this issue by ammending the ActionResult Create code from
public ActionResult Create()
{
ViewBag.CourseId = new SelectList(db.CourseViewModels, "CourseId", "CourseName");
return View();
}
To
public ActionResult Create()
{
var dbcourse = db.Course.ToList();
//Make selectlist, which is IEnumerable<SelectListItem>
var courseNameDropdownList = new SelectList(db.Course.Select(item => new SelectListItem()
{
Text = item.CourseName.ToString(),
Value = item.CourseId.ToString()
}).ToList(), "Value", "Text");
// Assign the Selectlist to the View Model
var viewCourse = new HoleViewModel()
{
Course = dbcourse.FirstOrDefault(),
// The Dropdownlist values
CourseNamesDropdownList = courseNameDropdownList,
};
//ViewBag.CourseId = new SelectList(db.CourseViewModels, "CourseId", "CourseName");
return View(viewCourse);
}
This has allowed the dropdown to be populated and be added to the view.

I am trying to log an audit table in SQL using MVC C# to track edits using the controller

So far I can save my edits from the Transaction table to the TransEdit table adding my TransEdit "Entity?", but cannot get the original value before it has been changed in the edit View form.
I'm not well versed with MVC so I'm not sure how to proceed. I am very lost. Any help is appreciated.
Currently my controller looks like this
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity.Migrations;
namespace WaterProject2.Models
{
public class TransactionsController : Controller
{
private omerDataEntities db = new omerDataEntities();
// GET: Transactions
public ActionResult Index()
{
return View(db.Transactions.ToList());
}
// GET: Transactions/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Transaction transaction = db.Transactions.Find(id);
if (transaction == null)
{
return HttpNotFound();
}
return View(transaction);
}
// GET: Transactions/Create
public ActionResult Create()
{
ViewBag.ReferenceIDs = new SelectList(db.Transactions, "Ref_ID","Ref_ID");
ViewBag.CompanyDroplist = new SelectList(db.Entities, "Entities","Entities");
ViewBag.CustomerDroplist = new SelectList(db.Transactions, "Customer", "Customer");
ViewBag.AssetDroplist = new SelectList(db.Assets, "Asset_Name", "Asset_Name");
ViewBag.DealsDroplist = new SelectList(db.deals, "Ref_ID", "Ref_ID");
return View();
}
// POST: Transactions/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Trans_Nbr,Ref_ID,TransDT,Company,Deal,Status,Trans_Lead,Customer,Vendor,Transaction_Type,Water_Type,Contract_AF,Gross_AF,Leave_Behind_AF,AF_Value,Location_IOU,Notes,Invoice_Nbr,Contract_Dt,Instructions,OTN,Asset_Nbr,Asset_Name,Asset_Type,Sub_Entity,Asset_Status")] Transaction transaction)
{
if (ModelState.IsValid)
{
db.Transactions.Add(transaction);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(transaction);
}
// GET: Transactions/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Transaction transaction = db.Transactions.Find(id);
if (transaction == null)
{
return HttpNotFound();
}
return View(transaction);
}
// POST: Transactions/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Trans_Nbr,Ref_ID,TransDT,Company,Deal,Status,Trans_Lead,Customer,Vendor,Transaction_Type,Water_Type,Contract_AF,Gross_AF,Leave_Behind_AF,AF_Value,Location_IOU,Notes,Invoice_Nbr,Contract_Dt,Instructions,OTN,Asset_Nbr,Asset_Name,Asset_Type,Sub_Entity,Asset_Status")] Transaction transaction)
{
Transaction origTrans = db.Transactions.Find(transaction.Trans_Nbr);
TransEdit newTransEdit = new TransEdit();
newTransEdit.Trans_Nbr = origTrans.Trans_Nbr + 10;
newTransEdit.Ref_ID = origTrans.Ref_ID;
newTransEdit.TransDT = origTrans.TransDT;
newTransEdit.Company = origTrans.Company;
newTransEdit.Deal = origTrans.Deal;
newTransEdit.Status = origTrans.Status;
newTransEdit.Trans_Lead = origTrans.Trans_Lead;
newTransEdit.Customer = origTrans.Customer;
newTransEdit.Vendor = origTrans.Vendor;
newTransEdit.Transaction_Type = origTrans.Transaction_Type;
newTransEdit.Water_Type = origTrans.Water_Type;
newTransEdit.Contract_AF = origTrans.Contract_AF;
newTransEdit.Gross_AF = origTrans.Gross_AF;
newTransEdit.Leave_Behind_AF = origTrans.Leave_Behind_AF;
newTransEdit.AF_Value = origTrans.AF_Value;
newTransEdit.Location_IOU = origTrans.Location_IOU;
newTransEdit.Notes = origTrans.Notes;
newTransEdit.Invoice_Nbr = origTrans.Invoice_Nbr;
newTransEdit.Contract_Dt = origTrans.Contract_Dt;
newTransEdit.Instructions = origTrans.Instructions;
newTransEdit.OTN = origTrans.OTN;
newTransEdit.Asset_Nbr = origTrans.Asset_Nbr;
newTransEdit.Asset_Name = origTrans.Asset_Name;
newTransEdit.Asset_Type = origTrans.Asset_Type;
newTransEdit.Sub_Entity = origTrans.Sub_Entity;
newTransEdit.Asset_Status = origTrans.Asset_Status;
db.Entry(newTransEdit).State = EntityState.Added;
db.SaveChanges();
if (ModelState.IsValid)
{
db.Set<Transaction>().AddOrUpdate(transaction);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(transaction);
}
// GET: Transactions/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Transaction transaction = db.Transactions.Find(id);
if (transaction == null)
{
return HttpNotFound();
}
return View(transaction);
}
// POST: Transactions/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Transaction transaction = db.Transactions.Find(id);
db.Transactions.Remove(transaction);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult SearchIndex(string searchString)
{
var TransSearch = from m in db.Transactions
select m;
if (!String.IsNullOrEmpty(searchString))
{
TransSearch = TransSearch.Where(s => s.Ref_ID.Contains(searchString));
}
return View(TransSearch);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
My Model
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WaterProject2.Models
{
using System;
using System.Collections.Generic;
public partial class Transaction
{
public int Trans_Nbr { get; set; }
public string Ref_ID { get; set; }
public System.DateTime TransDT { get; set; }
public string Company { get; set; }
public string Deal { get; set; }
public int Status { get; set; }
public string Trans_Lead { get; set; }
public string Customer { get; set; }
public string Vendor { get; set; }
public string Transaction_Type { get; set; }
public string Water_Type { get; set; }
public Nullable<int> Contract_AF { get; set; }
public Nullable<int> Gross_AF { get; set; }
public Nullable<int> Leave_Behind_AF { get; set; }
public Nullable<int> AF_Value { get; set; }
public string Location_IOU { get; set; }
public string Notes { get; set; }
public string Invoice_Nbr { get; set; }
public Nullable<System.DateTime> Contract_Dt { get; set; }
public string Instructions { get; set; }
public Nullable<int> OTN { get; set; }
public Nullable<decimal> Asset_Nbr { get; set; }
public string Asset_Name { get; set; }
public string Asset_Type { get; set; }
public string Sub_Entity { get; set; }
public string Asset_Status { get; set; }
}
}
and my view
#model WaterProject2.Models.Transaction
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Transaction</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Trans_Nbr)
<div class="form-group">
#* #Html.LabelFor(model => model.Ref_ID, htmlAttributes: new { #class = "control-label col-md-2" })*#
<div class="col-md-10">
#Html.HiddenFor(model => model.Ref_ID)
#* #Html.EditorFor(model => model.Ref_ID, new { htmlAttributes = new { #class = "form-control" } })*#
#* #Html.ValidationMessageFor(model => model.Ref_ID, "", new { #class = "text-danger" })*#
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TransDT, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TransDT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TransDT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Company, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Company, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Company, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Deal, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Deal, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Deal, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Status, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Status, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Status, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Trans_Lead, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Trans_Lead, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Trans_Lead, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Customer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Vendor, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Vendor, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Vendor, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Transaction_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Transaction_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Transaction_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Water_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Water_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Water_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Contract_AF, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Contract_AF, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Contract_AF, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gross_AF, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Gross_AF, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Gross_AF, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Leave_Behind_AF, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Leave_Behind_AF, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Leave_Behind_AF, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AF_Value, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AF_Value, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AF_Value, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location_IOU, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Location_IOU, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Location_IOU, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Notes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Notes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Notes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Invoice_Nbr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Invoice_Nbr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Invoice_Nbr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Contract_Dt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Contract_Dt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Contract_Dt, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Instructions, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Instructions, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Instructions, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OTN, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OTN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OTN, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Asset_Nbr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Asset_Nbr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Asset_Nbr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Asset_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Asset_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Asset_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Asset_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Asset_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Asset_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Sub_Entity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Sub_Entity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Sub_Entity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Asset_Status, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Asset_Status, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Asset_Status, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I edited the controller. This has been Solved.

Using many to many relationship in ASP.net

I'm trying to use Many-to-Many relationship, i succeded in editing and displaying a customer(name "client" on my code), but i can't create.
In my example, one customer(client) can be part of one or more societies.
Using Visual Studio step-by-step, i noticed that my values can't pass to my first "create" function to the second. I successfully getting the field i want to, but can't POST them.
My ClientController:
public ActionResult Create()
{
var cli = new ClientViewModel
{
Client = new Client()
};
var allSocietesList = db.Societes.ToList();
cli.AllSocietes = allSocietesList.Select(o => new SelectListItem
{
Text = o.Nom,
Value = o.ID.ToString()
});
ViewBag.StatutClientID = new SelectList(db.StatutClients, "ID", "Designation");
return View(cli);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ClientViewModel client) //Here is where the value dosesn't pass, "client" value is null;
{
if (ModelState.IsValid)
{
var cliToAdd = new Client();
var updatedSocietes = new HashSet<int>(client.SelectedSociete);
foreach (Societe societe in db.Societes)
{
if (updatedSocietes.Contains(societe.ID))
{
cliToAdd.Societes.Add((societe));
}
}
db.Clients.Add(cliToAdd);
db.Entry(cliToAdd).State = System.Data.Entity.EntityState.Added;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.StatutClientID = new SelectList(db.StatutClients, "ID", "Designation", client.Client.StatutClientID);
return View(client);
}
Now comes my Client Model:
namespace CRM.Models
{
public class Client : Personne // Héritage de la classe Personne
{
public Client()
{
this.Societes= new HashSet<Societe>();
}
[Column("StatutClientID")]
public int StatutClientID { get; set; }
public string Fonction { get; set; } // TODO:Type enum
[Display(Name = "Est Actif ?")]
public bool IsActif { get; set; }
[DataType(DataType.MultilineText)]
public string Commentaire { get; set; }
public string Fax { get; set; }
public virtual StatutClient StatutClient { get; set; }
public virtual ICollection<Societe> Societes { get; set; }
override public string ToString()
{
return this.Prenom+" "+this.Nom;
}
}
}
My class ViewModels i'm using in my controller:
namespace CRM.ViewModels
{
public class ClientViewModel
{
public Client Client { get; set; }
public IEnumerable<SelectListItem> AllSocietes { get; set; }
private List<int> selectedSociete;
public List<int> SelectedSociete
{
get
{
if (selectedSociete == null)
{
selectedSociete = Client.Societes.Select(m => m.ID).ToList();
}
return selectedSociete;
}
set { selectedSociete = value; }
}
}
}
And finally, my View :
#model CRM.ViewModels.ClientViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Client</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Client.Nom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Nom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Nom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Prenom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Prenom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Prenom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Fonction, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Fonction, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Fonction, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Commentaire, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Commentaire, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Commentaire, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Telephone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Fax, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Fax, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Fax, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Mail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Mail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Mail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.IsActif, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Client.IsActif)
#Html.ValidationMessageFor(model => model.Client.IsActif, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.StatutClientID, "StatutClient", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StatutClientID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Client.StatutClientID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AllSocietes, "JobTag", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(model => model.SelectedSociete, Model.AllSocietes)
</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>
}
<div>
#Html.ActionLink("Retour à la liste", "Index")
</div>
#section Scripts {
#System.Web.Optimization.Scripts.Render("~/bundles/jqueryval")
}
(My societies model (name "societe"), if you want to know what's on it, but the problem doesn't come from here, you can skip it).
namespace CRM.Models
{
public class Societe
{
public Societe()
{
this.Clients = new HashSet<Client>();
}
public int ID { get; set; }
public string Nom { get; set; }
//[Required] //TODO: renseigner adresse dans les societes de l'initializer
[Display(Name = "Lieu")]
public int LieuID { get; set; }
public string Adresse { get; set; }
public int Km { get; set; }
public string Temps { get; set; }
public bool IsActif { get; set; }
public virtual Lieu Lieu { get; set; }
public virtual ICollection<Affaire> Affaires { get; set; }
public virtual ICollection<Client> Clients { get; set; }
}
}
For successfully editing and displaying, i followed that tutorial:
https://www.codeproject.com/articles/702890/mvc-entity-framework-and-many-to-many-relation
If my problem isn't easy to understand because of my english or anything else, just ask :)
EDIT: Here is my editing function, which is 100% functionnal:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var clientViewModel = new ClientViewModel
{
Client = db.Clients.Include(i => i.Societes).First(i => i.ID == id)
};
if (clientViewModel.Client == null)
return HttpNotFound();
var allSocietesList = db.Societes.ToList();
clientViewModel.AllSocietes = allSocietesList.Select(o => new SelectListItem
{
Text = o.Nom,
Value = o.ID.ToString()
});
ViewBag.StatutClientID = new SelectList(db.StatutClients, "ID", "Designation", clientViewModel.Client.StatutClientID);
return View(clientViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ClientViewModel clientView)
{
if (clientView == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
var clientToUpdate = db.Clients
.Include(i => i.Societes).First(i => i.ID == clientView.Client.ID);
if (TryUpdateModel(clientToUpdate, "Client", new string[] { "Fonction", "Commentaire", "Nom", "Prenom", "Telephone", "Mobile", "Fax", "Mail", "IsActif", "StatutClientID" }))
{
// var newJobTags = db.Societes.Where(
// m => clientView.SelectedSociete.Contains(m.ID)).ToList();
var updatedSocietes = new HashSet<int>(clientView.SelectedSociete);
foreach (Societe societe in db.Societes)
{
if (!updatedSocietes.Contains(societe.ID))
{
clientToUpdate.Societes.Remove(societe);
}
else
{
clientToUpdate.Societes.Add((societe));
}
}
db.Entry(clientToUpdate).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
ViewBag.StatutClientID = new SelectList(db.StatutClients, "ID", "Designation", clientView.Client.StatutClientID);
return View(clientView);
}
And the Edit view associated:
#model CRM.ViewModels.ClientViewModel
#{
ViewBag.Title = "Edit";
}
<h2 class="well">Clients - Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Client.ID)
<div class="form-group">
#Html.LabelFor(model => model.Client.Fonction, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Fonction, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Fonction, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Commentaire, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Commentaire, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Commentaire, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Nom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Nom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Nom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Prenom, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Prenom, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Prenom, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Telephone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Telephone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Telephone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Fax, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Fax, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Fax, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.Mail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Client.Mail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Client.Mail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.IsActif, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Client.IsActif)
#Html.ValidationMessageFor(model => model.Client.IsActif, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Client.StatutClientID, "Client.StatutClientID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.Client.StatutClientID,
(SelectList)ViewBag.StatutClientID,
Model.Client.StatutClient.ID);
#*Html.DropDownList("Client.StatutClientID", null, htmlAttributes: new { #class = "form-control" })*#
#Html.ValidationMessageFor(model => model.Client.StatutClientID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AllSocietes, "JobTag", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(m => m.SelectedSociete, Model.AllSocietes)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Retour à la liste", "Index")
</div>
#section Scripts {
#System.Web.Optimization.Scripts.Render("~/bundles/jqueryval")
}
The only problem i can see is with your view, the rest seems ok to me.
First off, i often specify how my form is going to be posted and where
#using (Html.BeginForm("Action_name", "Controler_name", FormMethod.Post, new { role = "form" }))
{
}
Then, you also should put the id of your model in the page. This is something i now ALWAYS do. It's more coherent. And if you skip that part, your id won't be available, the page is the only way to keep it from disapearing.
something like :
#Html.HiddenFor(t => t.client.id)
Put these for all your model instances you wish to be passed back to your form without having it displayed. I don't know it will solve your problem COMPLETLY, but it's a good start.

ASP.NET MVC 5 Set values for dropdownlist

I want to make a DropDownList with a numeric rating from 1-5. I have a rating model and I want to apply these dropdown values to WaitTime, Attentive and Outcome.
Can I just set these values in the view and use the model? If so how would i go about doing this?
My Model Class:
public class Ratings
{
//Rating Id (PK)
public int Id { get; set; }
public string UserId { get; set; }
//Medical Practice (FK)
public int MpId { get; set; }
public MP MP { get; set; }
//User ratings (non-key values)
[Required] //Adding Validation Rule
public int WaitTime { get; set; }
[Required] //Adding Validation Rule
public int Attentive { get; set; }
[Required] //Adding Validation Rule
public int Outcome { get; set; }
}
My View:
<div class="form-group">
#Html.LabelFor(model => model.WaitTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.WaitTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WaitTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Attentive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Attentive, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Attentive, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Outcome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Outcome, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Outcome, "", new { #class = "text-danger" })
</div>
</div>
Use this instead of EditorFor for each field:
#Html.DropDownListFor(model => model.Outcome, new SelectList(Enumerable.Range(1, 5)))
Here is the working fiddle - https://dotnetfiddle.net/daB2DI
In short, lets say your model is -
public class SampleViewModel
{
[Required] //Adding Validation Rule
public int WaitTime { get; set; }
[Required] //Adding Validation Rule
public int Attentive { get; set; }
[Required] //Adding Validation Rule
public int Outcome { get; set; }
}
And your controller actions are -
[HttpGet]
public ActionResult Index()
{
return View(new SampleViewModel());
}
[HttpPost]
public JsonResult PostData(SampleViewModel model)
{
return Json(model);
}
Your Get CSHTML should be -
#model HelloWorldMvcApp.SampleViewModel
#{
ViewBag.Title = "GetData";
}
<h2>GetData</h2>
#{
var items = new List<SelectListItem>();
for (int i = 1; i < 6; i++)
{
var selectlistItem = new SelectListItem();
var code = 0;
selectlistItem.Text = (code + i).ToString();
selectlistItem.Value = (code + i).ToString();
items.Add(selectlistItem);
}
}
#using (Html.BeginForm("PostData","Home"))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SampleViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.WaitTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.WaitTime, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.WaitTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Attentive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Attentive, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Attentive, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Outcome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Outcome, items, "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Outcome, "", 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>
}
When you run the code, you should see page like below -
And when you select some values and click on create, you should get those values in PostData action.
try to adapt this to your project
in your controller:
ViewBag.ParentID = new SelectList(departmentsQuery, "NewsMID", "Title", selectedDepartment);
return View(model);
in your view put this
#Html.DropDownList("ParentID")

Slightly more complex "create" form in ASP.NET w/Entity Framework and MVC

Here is a sample of my models. There is a Supply Receipt that holds custom models for Block, Grower, and a collection of SupplyReceiptLine:
public class SupplyReceipt
{
[Key]
public int Id { get; set; }
[Required]
public string LoadNumber { get; set; }
[Required]
public DateTime Date { get; set; }
public string Notes { get; set; }
[Required]
public Block Block { get; set; }
[Required]
public Contact Grower { get; set; }
[Required]
public ICollection<SupplyReceiptLine> SupplyReceiptLines { get; set; }
}
And I don't think it's necessary for my question but here is an example for my Contact model (used for Grower):
public class Contact
{
[Key]
public int Id { get; set; }
[Required]
public string Title { get; set; }
public string Note { get; set; }
[Display(Name="Billing Address")]
public virtual Address BillingAddress { get; set; }
[Display(Name = "Shipping Address")]
public virtual Address ShippingAddress { get; set; }
[Display(Name = "Show as Supplier")]
public bool IsSupplier { get; set; }
[Display(Name = "Show as Customer")]
public bool IsCustomer { get; set; }
[Display(Name = "Show as Grower")]
public bool IsGrower { get; set; }
[Display(Name = "Show as Bin Owner")]
public bool IsBinOwner { get; set; }
}
Now I'm having multiple problems:
Regular MVC Scaffolding (Entity Framework Model) doesn't like Grower, Block, or Supply Receipt Lines. I understand Supply Receipt Lines needs logic behind it, but I don't understand why I had to work so hard to create a drop down select box for Grower and Block. These types are well defined (with Ids and Key attributes) and there is data in the database for these items.
Could anyone explain what I'm missing in my model above that MVC / EF Scaffolding doesn't understand? A lot of tutorials online show this automatically being done. I had to resort to manually placing an Html.DropDownListFor in my view, passing it a new SelectList built from my database context. I also had to update the controller post method to include an integer for Grower and integer for Block, and manually lookup the Grower & Block by id, assign them back to the model, before adding my Supply Receipt to the database.
I couldn't figure this out. Supply Receipt Lines is an ICollection, it should hold multiple Supply Receipt Line. How do I update my create view, and my controller, so that I can add multiple supply receipt lines within this same form?
Here is an example screenshot to go along with number 2:
Here is some of the other code associated with this "create" method, including the editors. Thanks for your time.
(Controller Post Method)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(SupplyReceipt supplyReceipt, int Grower, int Block, ICollection<SupplyReceiptLine> supplyReceiptLines)
{
// supplyReceiptLines turns up null! So does supplyReceipt.SupplyReceiptLines
// Need Grower and Block For Some reason
supplyReceipt.Grower = db.Contacts.Where(model => model.Id.Equals(Grower)).First();
supplyReceipt.Block = db.Blocks.Where(model => model.Id.Equals(Block)).First();
if (ModelState.IsValid)
{
db.SupplyReceipts.Add(supplyReceipt);
if (supplyReceiptLines != null && supplyReceiptLines.Any())
{
db.SupplyReceiptLines.AddRange(supplyReceiptLines);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(supplyReceipt);
}
(Create Form)
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>SupplyReceipt</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.LoadNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LoadNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LoadNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Grower, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Grower, new SelectList(Db.Contacts, "Id", "Title"), "Select a Grower", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Grower, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Block, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Block, new SelectList(Db.Blocks, "Id", "Title"), "Select a Block", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Block, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Notes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Notes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Notes, "", new { #class = "text-danger" })
</div>
</div>
<hr />
<div id="supplyReceiptLines">
#Html.EditorFor(model => model.SupplyReceiptLines, "SupplyReceiptLines")
</div>
<div class="form-group text-right">
Add a row
</div>
<hr />
<div class="form-group">
<div class="text-right">
<button type="submit" value="Create" class="btn btn-default btn-success">Create Supply Receipt</button>
</div>
</div>
</div>
}
(Editor Template)
#model SupplyReceiptLine
#{
ModelContext Db = new ModelContext();
}
<div class="form-group form-inline">
#Html.HiddenFor(model => model.Id)
<div class="col-sm-1">
#Html.LabelFor(model => model.Qty, htmlAttributes: new { #class = "" })
#Html.EditorFor(model => model.Qty, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Qty, "", new { #class = "text-danger" })
</div>
<div class="col-sm-1">
#Html.LabelFor(model => model.Pack, htmlAttributes: new { #class = "" })
#Html.DropDownListFor(model => model.Pack, new SelectList(Db.Packs, "Id", "Title"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Pack, "", new { #class = "text-danger" })
</div>
<div class="col-sm-1">
#Html.LabelFor(model => model.Size, htmlAttributes: new { #class = "" })
#Html.DropDownListFor(model => model.Size, new SelectList(Db.Sizes, "Id", "Title"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Size, "", new { #class = "text-danger" })
</div>
<div class="col-sm-3">
#Html.LabelFor(model => model.Variety, htmlAttributes: new { #class = "" })
#Html.DropDownListFor(model => model.Variety, new SelectList(Db.Varieties, "Id", "Title"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Variety, "", new { #class = "text-danger" })
</div>
<div class="col-sm-3">
#Html.LabelFor(model => model.Grade, htmlAttributes: new { #class = "" })
#Html.DropDownListFor(model => model.Grade, new SelectList(Db.Grades, "Id", "Title"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Grade, "", new { #class = "text-danger" })
</div>
<div class="col-sm-3">
#Html.LabelFor(model => model.BinOwner, htmlAttributes: new { #class = "" })
#Html.DropDownListFor(model => model.BinOwner, new SelectList(Db.Contacts, "Id", "Title"), "", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BinOwner, "", new { #class = "text-danger" })
</div>
</div>

Categories

Resources