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.
Related
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Why is EditorFor in my ASP.NET MVC 2 application throwing ArgumentNullException?
(1 answer)
Closed 2 years ago.
I have a pretty simple program so far, meaning it shouldn't be too hard to find the problem.
When I load the website I get the following error on line 21 of the SignUp view:
#Html.EditorFor(model => model.EmployeeId, new { htmlAttributes = new { #class = "form-control" } })
System.NullReferenceException: 'Object reference not set to an instance of an object.'
The model class
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
namespace MVCApp.Models
{
public class EmployeeModel
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string ConfirmEmail { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
}
}
The controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCApp.Controllers
{
public class HomeController : Controller
{
...
public ActionResult SignUp()
{
ViewBag.Message = "Employee Sign Up";
return View();
}
}
}
The view (autogenerated)
#model MVCApp.Models.EmployeeModel
#{
ViewBag.Title = "Employee Sign Up";
}
<h2>SignUp</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>EmployeeModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.EmployeeId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmployeeId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmployeeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmailAddress, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmailAddress, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmailAddress, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmEmail, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmEmail, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmEmail, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ConfirmPassword, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ConfirmPassword, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ConfirmPassword, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I'm using Microsoft Visual Studio Community 2019 Version 16.7.2 and .NET Framework 4.7.2
Thank you
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.
I have a fairly simple form and ViewModel which works fine, but when I add this JS, the form no longer submits to the controller:
$("#crmtForm").submit(function (e) {
console.log('submit');
});
Why? I'm pretty sure this is supposed to work... Please can someone help this makes no sense.
Controller
[HttpPost]
public async Task<ActionResult> Create(CRMTItemViewModel viewModel)
{
viewModel.CreatedBy = System.Security.Claims.ClaimsPrincipal.Current.Claims.FirstOrDefault(c => c.Type == "name").Value;
if (viewModel.ProjectTitle == "spinnertest")
return View();
// Insert db rows?
var crmtItem = await crmtItemsManager.InsertItem(viewModel);
// Initialise workspace on a seperate thread
new Thread(() =>
{
var projectManager = new ProjectManager();
projectManager.ProcessRequest(crmtItem);
}).Start();
// Redirect to item
return RedirectToAction("Details", new { id = crmtItem.Id });
}
Form
#using (Html.BeginForm("Create", "CrmtItems", FormMethod.Post, new { id = "crmtForm" }))
{
<div class="form-horizontal">
<h4>New Project Workspace Form</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProjectTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProjectTitle, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.ProjectTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProjectStage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EnumDropDownListFor(model => model.ProjectStage, new { #class = "form-control", required = "required" })
#Html.ValidationMessageFor(model => model.ProjectStage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CRMTNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CRMTNumber, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.CRMTNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GbSNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.GbSNumber, new { htmlAttributes = new { #class = "form-control", required = "required" } })
#Html.ValidationMessageFor(model => model.GbSNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Confidential, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Confidential, new { #class = "form-control", #style = "height:17px;" })
#Html.ValidationMessageFor(model => model.Confidential, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => Model.SelectedTags, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(m => m.Id, new { required = "required" })
#Html.ListBoxFor(m => m.SelectedTags, new SelectList(users, "UserName", "DisplayName"), new { #class = "teamSelecter", name = "states[]", multiple = "multiple", style = "display:none; width:100%;", required = "required" })
#Html.ValidationMessageFor(model => model.SelectedTags, "", new { #class = "text-danger" })
<p id="pmWarning" class="text-danger" hidden>Please select one or more project managers</p>
</div>
</div>
<br />
<button id="formSubmit" class="btn btn-default btn-lg pull-right" type="submit" value="submit">Submit</button>
<div class="loader pull-right" hidden></div>
</div>
}
ViewModel
public class CRMTItemViewModel
{
public int Id { get; set; }
[Display(Name = "Project Title")]
[Remote("DoesProjectTitleExist", "CRMTItems", HttpMethod = "POST",
ErrorMessage = "Workspace for that project title already exists.")]
public string ProjectTitle { get; set; }
[Display(Name = "Project Stage")]
public ProjectStage? ProjectStage { get; set; }
[Display(Name = "CRMT Number")]
[Remote("DoesCrmtNumberExist", "CRMTItems", HttpMethod = "POST",
ErrorMessage = "Workspace for that CRMT number already exists.")]
public int? CRMTNumber { get; set; }
[Display(Name = "GBS Number")]
[Remote("DoesGbSNumberExist", "CRMTItems", HttpMethod = "POST",
ErrorMessage = "Workspace for that GBS project number already exists.")]
public int? GbSNumber { get; set; }
public bool Confidential { get; set; }
[Display(Name = "Project Managers")]
public IEnumerable<string> SelectedTags { get; set; }
}
I tried your code in my project its working,may be issue with your jquery version,one more thing I found when I was created scaffolding view with this model it automatically created #section Scripts {
#Scripts.Render("~/bundles/jqueryval")
} at end of view page,
when I removed this script from page then able to call post method otherwise not.
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}")]
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")