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.
Related
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 am quite new to asp.net mvc5, and in my app I want to retrieve user info in their profile.
In profile action I'm trying to display the user info and allow them to edit their info too.
But when I run the program I am getting the edit and display view empty.
I am expecting to see the user previous info when they're trying to edit for example.
here is a picture of what I want:
this is my action :
[HttpGet]
public ActionResult DriverProfile()
{
var userManager = HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
var authManager = HttpContext.GetOwinContext().Authentication;
ProfileModel driver = new ProfileModel();
IdentityUser theUser = new IdentityUser() { UserName = driver.email, Email = driver.email };
driver = new ProfileModel(theUser);
return View("DriverProfile", driver);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DriverProfile(ProfileModel profile)
{
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(new RidesDbContext()));
IdentityUser theUser = new IdentityUser() { UserName = profile.email, Email = profile.email };
IdentityResult theResult = manager.Create(theUser, profile.PasswordHash);
var currentUser = manager.FindById(User.Identity.GetUserId());
currentUser.UserName = profile.email;
currentUser.Email = currentUser.Email;
return Redirect("DriverProfile");
}
I have the profile model as the following:
public class ProfileModel
{
public ProfileModel()
{
}
public ProfileModel(IdentityUser theUser)
{
}
[Display(Name = "Id")]
public int driverId { get; set; }
[Display(Name = "First Name")]
[Required(ErrorMessage = "Pleas Enter Your First Name")]
public string firstName { get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "Pleas Enter Your Last Name")]
public string lastName { get; set; }
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress)]
[Required(ErrorMessage = "Pleas Enter Your Email Address")]
[RegularExpression(".+\\#.+\\..+", ErrorMessage = "Please Enater a Valid Email Address")]
public string email { get; set; }
[Display(Name = "Mobile Number")]
[Required(ErrorMessage = "Pleas Enter Your Mobile Number")]
public string phoneNumber { get; set; }
[Display(Name = "Address")]
[Required(ErrorMessage = "Pleas Enter Your Address")]
public string Address { get; set; }
[Display(Name = "City")]
[Required(ErrorMessage = "Pleas Enter Your City")]
public string city { get; set; }
[Display(Name = "State")]
[Required(ErrorMessage = "Pleas Enter Your state")]
public string state { get; set; }
[Display(Name = "Car")]
[Required(ErrorMessage = "Please Identify Your Car")]
public string car { get; set; }
[Display(Name = "Driver's License")]
[Required(ErrorMessage = "Please Enter Your Driver's Licende Number")]
public string driverslicense { get; set; }
[Display(Name = "Profile Image")]
[Required]
public byte[] profileImg { get; set; }
public string profileImgType { get; set; }
[Display(Name = "License Image")]
[Required]
public byte[] licenseImg { get; set; }
public string licenseImgType { get; set; }
[Display(Name = "Password")]
[DataType(DataType.Password)]
[Required(ErrorMessage = "Please Enter a password")]
public string PasswordHash { get; set; }
}
How would I get the user info in their profile with an edit option?
I would appreciate your help. Thank you.
Edit:
the view is as the following:
#model RidesApp.Models.ProfileModel
#{
ViewBag.Title = "DriverProfile";
Layout = "~/Views/Shared/DriversViewPage.cshtml";
}
<h2>DriverProfile</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ProfileModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.driverId)
<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.email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.phoneNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.phoneNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.phoneNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.city, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.city, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.city, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.state, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.state, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.state, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.car, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.car, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.car, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.driverslicense, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.driverslicense, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.driverslicense, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.profileImgType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.profileImgType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.profileImgType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.licenseImgType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.licenseImgType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.licenseImgType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.PasswordFor(model => model.PasswordHash, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PasswordHash, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Edit Profile" class="btn btn-default" />
</div>
</div>
</div>
}
If I understand the question correctly, You want to edit the IdentityUser Class right?
Given that you already assign values in your controller.
First, we add the IdentityUser class to your ProfileModel Class
public class ProfileModel{
public IdentityUser User{get;set;}
//other profilemodel properties
}
on your view:
<div class="form-group">
#Html.LabelFor(model => model.User.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.User.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.User.Email, "", new { #class = "text-danger" })
</div>
</div>
or if you just want to show up some values in editing,
you need to assign the value of your ProfileModel
Controller:
ProfileModel driver = new ProfileModel();
//code that assigns values to each property
driver.email = "sample#sample.com";
return View("DriverProfile",driver);
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.
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")
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>