edit profile view asp.net-mvc5 - c#

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

Related

How to upload or download files from a view without being in the model

I'm working on an application that relies on an existing SQL Server database. I have created the Model, the Controller and a Create View using the Entity Frameworks code-first approach in Visual Studio. At the moment the code works for all fields and accepts null for the fields that should contain the path to external files (not in the DB).
The Model:
namespace Centurion.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
[Table("Fontane")]
public partial class Fontane
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Fontane()
{
Interventi = new HashSet<Interventi>();
}
[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FontanaID { get; set; }
private string _CodificaSIMU;
[StringLength(20)]
public string CodificaSIMU
{
get
{
if (string.IsNullOrEmpty(_CodificaSIMU))
{
return _CodificaSIMU;
}
return _CodificaSIMU.ToUpper();
}
set
{
_CodificaSIMU = value;
}
}
//public string CodificaSIMU { get; set; }
[Required]
[StringLength(255)]
public string Nome { get; set; }
[StringLength(255)]
public string Indirizzo { get; set; }
public int? Municipio { get; set; }
[Required]
public double Latitudine { get; set; }
[Required]
public double Longitudine { get; set; }
[Required]
public int TipoFontana { get; set; }
[Required]
public int TipoImpianto { get; set; }
[Required]
public int Frequenza { get; set; }
[Required]
public bool Svuotamento { get; set; }
public bool? Active { get; set; }
public bool? Allarme { get; set; }
[StringLength(255)]
public string Foto { get; set; }
[StringLength(255)]
public string Allegato1 { get; set; }
[StringLength(255)]
public string Allegato2 { get; set; }
public string Note { get; set; }
[Required]
public int UserIDCrea { get; set; }
[Required]
public DateTime DataCrea { get; set; }
[Required]
public int UserIDModifica { get; set; }
[Required]
public DateTime DataModifica { get; set; }
public virtual Municipi Municipi { get; set; }
public virtual TipiFontana TipiFontana { get; set; }
public virtual Impianto Impianto { get; set; }
public virtual Utenti Utenti { get; set; }
public virtual Utenti Utenti1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Interventi> Interventi { get; set; }
}
public class FontaneFiles
{
[DataType(DataType.Upload)]
[Display(Name = "Upload Foto")]
public string FotoFile { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Upload Allegato1")]
public string All1File { get; set; }
[DataType(DataType.Upload)]
[Display(Name = "Upload Allegato2")]
public string All2File { get; set; }
}
}
As you can see I have added a second class for uploading the files since the relative table in the DB has just a string for the path in the server.
This is the code of my controller which works fine except the file upload part:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Crea([Bind(Include = "FontanaID,CodificaSIMU,Nome,Indirizzo,Municipio,Latitudine,Longitudine,TipoFontana,TipoImpianto,Frequenza,Svuotamento,Foto,Allegato1,Allegato2,Note")] Fontane fontane)
//public ActionResult Crea([Bind(Include = "FontanaID,CodificaSIMU,Nome,Indirizzo,Municipio,Latitudine,Longitudine,TipoFontana,TipoImpianto,Frequenza,Svuotamento,Active,Allarme,Foto,Allegato1,Allegato2,Note,UserIDCrea,DataCrea,UserIDModifica,DataModifica")] Fontane fontane)
{
// to be replaced in production mode with logged user
fontane.UserIDCrea = cUser;
fontane.UserIDModifica = cUser;
// set date as NOW
fontane.DataCrea = DateTime.Now;
fontane.DataModifica = DateTime.Now;
// no allarm when creating
fontane.Allarme = false;
// active when creating
fontane.Active = true;
fontane.Latitudine = Convert.ToDouble(fontane.Latitudine);
fontane.Longitudine = Convert.ToDouble(fontane.Longitudine);
if (ModelState.IsValid)
{
try
{
db.Fontane.Add(fontane);
db.SaveChanges();
return RedirectToAction("Indice");
}
catch (DbUpdateException)
{
ModelState.AddModelError(string.Empty, "Fontana esistente!");
}
catch (Exception ex)
{
return View("Error", new HandleErrorInfo(ex, "Fontane", "Crea"));
}
return View();
}
ViewBag.TipoImpianto = new SelectList(db.Impianto, "ImpiantoID", "Impianto1", fontane.TipoImpianto);
ViewBag.Municipio = new SelectList(db.Municipi, "MunicipioID", "Municipio", fontane.Municipio);
ViewBag.TipoFontana = new SelectList(db.TipiFontana, "TipoID", "Descrizione", fontane.TipoFontana);
ViewBag.UserIDCrea = new SelectList(db.Utenti, "UserID", "UserName", fontane.UserIDCrea);
ViewBag.UserIDModifica = new SelectList(db.Utenti, "UserID", "UserName", fontane.UserIDModifica);
return View(fontane);
}
The View:
#model Centurion.Models.Fontane
#{
ViewBag.Title = "Crea";
}
<h2>Aggiungi Fontana</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CodificaSIMU, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CodificaSIMU, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CodificaSIMU, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Nome, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Nome, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Nome, "", new { #class = "text-danger" })
</div>
</div>
<fieldset>
<legend>Ubicazione</legend>
<div class="form-group">
#Html.LabelFor(model => model.Indirizzo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Indirizzo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Indirizzo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Municipio, "Municipio", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Municipio", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Municipio, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Latitudine, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Latitudine, new
{
htmlAttributes = new
{
placeholder = "Latitudine = 41,..... (con la virgola)",
#class = "form-control"
}
})
#Html.ValidationMessageFor(model => model.Latitudine, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Longitudine, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Longitudine, new
{
htmlAttributes = new
{
placeholder = "Longitudine = 12,..... (con la virgola)",
#class = "form-control"
}
})
#Html.ValidationMessageFor(model => model.Longitudine, "", new { #class = "text-danger" })
</div>
</div>
</fieldset>
<div class="form-group">
#Html.LabelFor(model => model.TipoFontana, "TipoFontana", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TipoFontana", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TipoFontana, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TipoImpianto, "TipoImpianto", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TipoImpianto", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TipoImpianto, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Frequenza, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Frequenza, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Frequenza, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Svuotamento, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Svuotamento)
#Html.ValidationMessageFor(model => model.Svuotamento, "", new { #class = "text-danger" })
</div>
</div>
</div>
#Html.HiddenFor(m => m.Active)
#Html.HiddenFor(m => m.Allarme)
<div class="form-group">
#Html.LabelFor(model => model.Foto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Foto, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Foto, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Allegato1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Allegato1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Allegato1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Allegato2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Allegato2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Allegato2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Note, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Note, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Note, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(m => m.UserIDCrea)
#Html.HiddenFor(m => m.DataCrea)
#Html.HiddenFor(m => m.UserIDModifica)
#Html.HiddenFor(m => m.DataModifica)
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Crea" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Elenco Fontane", "Indice")
</div>
I can't change the DB table but I need to find a way to trigger the upload of an image and other files (should be pdf or Excel). Files will be stored in the subfolders of the app_data folder.
If I add the files to the same class of Fontane, I get a table error. I tried to combine the two classes with a tuple but I don't have any idea how to manage them in the Controller. Any help will be apreciated.

.submit() Prevents Form from Submitting

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.

c# MVC Entity Framework - Show only correct child records

I'm new to MVC and Entity framework and i am building my first web app with those 2 technologies. I am following a great tutorial (database first) and i have my basic application working now. But there is something the tutorial doesn't talk about.
Let's take this scenario:
I have 3 tables: Cars, Manufacturers, Models.
When i go to the auto generated view for create a new car, i have the correct dropdowns to enter the manufacturer and the model. But the dropdown with the models list is showing all the models and not just the ones related to the manufacturer i chose.
MODELS
Models
using System;
using System.Collections.Generic;
public partial class model
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public model()
{
this.cars = new HashSet<car>();
this.versions = new HashSet<version>();
}
public int id { get; set; }
public string name { get; set; }
public Nullable<int> manufacturerId { get; set; }
public bool active { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<car> cars { get; set; }
public virtual manufacturer manufacturer { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<version> versions { get; set; }
}
Manufacturers
using System;
using System.Collections.Generic;
public partial class manufacturer
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public manufacturer()
{
this.cars = new HashSet<car>();
this.models = new HashSet<model>();
}
public int id { get; set; }
public string name { get; set; }
public bool active { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<car> cars { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<model> models { get; set; }
}
Cars
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class car
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public car()
{
this.carimages = new HashSet<carimage>();
}
public int id { get; set; }
[Display(Name = "#")]
public Nullable<int> bodytypeId { get; set; }
[Display(Name = "Body Type")]
public Nullable<int> manufacturerId { get; set; }
[Display(Name = "Model")]
public Nullable<int> modelId { get; set; }
[Display(Name = "Version")]
public Nullable<int> versionId { get; set; }
[Display(Name = "Fuel")]
public Nullable<int> fuelId { get; set; }
[Display(Name = "Transmission")]
public Nullable<int> transmissionId { get; set; }
[Display(Name = "Color")]
public Nullable<int> colorId { get; set; }
[Display(Name = "HP")]
public Nullable<int> horsePower { get; set; }
[Display(Name = "KW")]
public Nullable<int> kw { get; set; }
[Display(Name = "CC")]
public Nullable<int> cc { get; set; }
[Display(Name = "CO2")]
public Nullable<double> Co2Emissions { get; set; }
[Display(Name = "Mileage")]
public Nullable<int> mileage { get; set; }
[Display(Name = "Year")]
public Nullable<int> year { get; set; }
[Display(Name = "Doors")]
public Nullable<int> doors { get; set; }
[Display(Name = "Seats")]
public Nullable<int> seats { get; set; }
[Display(Name = "Plate")]
public string plate { get; set; }
[Display(Name = "Price")]
public Nullable<int> price { get; set; }
[Display(Name = "Short Description")]
public string shortDescription { get; set; }
[Display(Name = "Long Description")]
public string longDescription { get; set; }
[Display(Name = "Sold")]
public bool sold { get; set; }
[Display(Name = "Active")]
public bool active { get; set; }
[Display(Name = "Date Added")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy hh:mm}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> dateAdded { get; set; }
[Display(Name = "Date Sold")]
[DataType(DataType.DateTime)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy hh:mm}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> dateSold { get; set; }
public virtual bodytype bodytype { get; set; }
public virtual color color { get; set; }
public virtual fuel fuel { get; set; }
public virtual manufacturer manufacturer { get; set; }
public virtual model model { get; set; }
public virtual transmission transmission { get; set; }
public virtual version version { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<carimage> carimages { get; set; }
}
CONTROLLER
Cars
// GET: cars/Create
public ActionResult Create()
{
ViewBag.bodytypeId = new SelectList(db.bodytypes, "id", "name");
ViewBag.colorId = new SelectList(db.colors, "id", "name");
ViewBag.fuelId = new SelectList(db.fuels, "id", "name");
ViewBag.manufacturerId = new SelectList(db.manufacturers, "id", "name");
ViewBag.modelId = new SelectList(db.models, "id", "name");
ViewBag.transmissionId = new SelectList(db.transmissions, "id", "name");
ViewBag.versionId = new SelectList(db.versions, "id", "name");
return View();
}
// POST: cars/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,bodytypeId,manufacturerId,modelId,versionId,fuelId,transmissionId,colorId,horsePower,kw,cc,Co2Emissions,mileage,year,doors,seats,plate,price,shortDescription,longDescription,sold,active,dateAdded,dateSold")] car car)
{
if (ModelState.IsValid)
{
db.cars.Add(car);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.bodytypeId = new SelectList(db.bodytypes, "id", "name", car.bodytypeId);
ViewBag.colorId = new SelectList(db.colors, "id", "name", car.colorId);
ViewBag.fuelId = new SelectList(db.fuels, "id", "name", car.fuelId);
ViewBag.manufacturerId = new SelectList(db.manufacturers, "id", "name", car.manufacturerId);
ViewBag.modelId = new SelectList(db.models, "id", "name", car.modelId);
ViewBag.transmissionId = new SelectList(db.transmissions, "id", "name", car.transmissionId);
ViewBag.versionId = new SelectList(db.versions, "id", "name", car.versionId);
return View(car);
}
VIEW
Create Car
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>car</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.bodytypeId, "bodytypeId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("bodytypeId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.bodytypeId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.manufacturerId, "manufacturerId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("manufacturerId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.manufacturerId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.modelId, "modelId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("modelId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.modelId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.versionId, "versionId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("versionId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.versionId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.fuelId, "fuelId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("fuelId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.fuelId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.transmissionId, "transmissionId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("transmissionId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.transmissionId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.colorId, "colorId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("colorId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.colorId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.horsePower, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.horsePower, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.horsePower, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.kw, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.kw, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.kw, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cc, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.cc, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.cc, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Co2Emissions, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Co2Emissions, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Co2Emissions, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.mileage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.mileage, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.mileage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.year, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.year, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.year, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.doors, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.doors, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.doors, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.seats, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.seats, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.seats, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.plate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.plate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.plate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.shortDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.shortDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.shortDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.longDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.longDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.longDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.sold, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.sold)
#Html.ValidationMessageFor(model => model.sold, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.active, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.active)
#Html.ValidationMessageFor(model => model.active, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dateAdded, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dateAdded, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateAdded, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.dateSold, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.dateSold, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.dateSold, "", 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 problem is in the controller in this line:
ViewBag.modelId = new SelectList(db.models, "id", "name");
This loads all available models from the db as options. I guess you do not know the manufacturer at this point. (Else you can add a simple where clause here: db.models.Where(mdl => mdl.manufacturer == knownManufacturer)).
A solution to filter the options on the client side would be to add the manufacturer as additional html attribute to the <option> tags for the models. adding html class tag under option in html dropdownlist
Then use javascript that listens to changes of the manufacturer dropdown and hides all options that do not match the selected manufacturer.

MVC Data Annotations in Razor

I'm trying to use Data Annotations in my MVC project (Mono/.NET 4.5). I've created my model and added all the appropriate annotations. I have my view and controller appropriately wired up. However, the validation just doesn't seem to be happening. I've tried everything I can find to no avail. As this is my first time working with Razor and Data Annotations, I imagine there is some setup piece I'm missing but I can't find it for the life of me. Here's my code:
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MyWebsite
{
public class RegisterViewModel : BaseViewModel
{
#region properties
[Required(ErrorMessage = "Required")]
[StringLength(50)]
[DisplayName("First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Required")]
[StringLength(100)]
[DisplayName("Last Name")]
public string LastName { get; set; }
[StringLength(50)]
[DisplayName("Display Name")]
public string DisplayName { get; set; }
[Required(ErrorMessage = "Required")]
[StringLength(255)]
[DisplayName("Email Address")]
public string EmailAddress { get; set; }
#endregion
#region ctor
public RegisterViewModel ()
{
}
#endregion
}
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyWebsite.Controllers
{
public class AccountController : Controller
{
public ActionResult Register()
{
ViewData ["IsComplete"] = false;
ViewData ["RequiredVouches"] = WebSettings.RequiredVouches;
return View ();
}
[HttpPost]
public ActionResult Register(FormCollection formData)
{
if (ModelState.IsValid) {
//TODO: Put the data
ViewData ["IsComplete"] = true;
}
return View ();
}
}
}
View
#model SummerIsles.Web.RegisterViewModel
#section Styles {
<link href="~/Content/themes/base/Account.css" rel="stylesheet" type="text/css" />
}
#{
if((bool)#ViewData["IsComplete"]) {
<h1>Registration Request Complete!</h1>
<div class="page-message">
<p>
Confirmation message goes here
</p>
</div>
}
else {
<h1>Registration</h1>
<div class="page-message">
<p>
Instruction text goes here
</p>
</div>
using (Html.BeginForm()) {
#Html.ValidationSummary(false)
<fieldset>
<legend>Your Information</legend>
<div class="group column-1">
#Html.LabelFor(modelItem => #Model.FirstName)
#Html.EditorFor(modelItem => #Model.FirstName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.FirstName)
#Html.LabelFor(modelItem => #Model.DisplayName)
#Html.EditorFor(modelItem => #Model.DisplayName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.DisplayName)
</div>
<div class="group column-2">
#Html.LabelFor(modelItem => #Model.LastName)
#Html.EditorFor(modelItem => #Model.LastName, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.LastName)
#Html.LabelFor(modelItem => #Model.EmailAddress)
#Html.EditorFor(modelItem => #Model.EmailAddress, new { htmlAttributes = new { #class="form-control" } } )
#Html.ValidationMessageFor(modelItem => #Model.EmailAddress)
</div>
<div class="button-options">
<button id="btnSubmit" type="submit" formmethod="post" class="btn btn-danger">Submit</button>
<a id="btnCancel" href="~/" class="btn">Cancel</a>
</div>
</fieldset>
}
}
}
Also, I have added the jquery validation scripts to my layout file and have also enabled client validation in the web.confg.
Layout Header
<head>
<!--some other css and such-->
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobstrusive.min.js"></script>
</head>
Web.config
<appSettings>
<!--some other stuff-->
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
Basically, when I click submit, it thinks the model is perfectly valid (ModelState.IsValid returns true in the controller) and the validation stuff (which I would expect to fire before the post back to the controller) never seems to fire. I get no validation messages even with a completely blank form (despite having the "Required" data annotation). What am I missing?
#Html.ValidationMessageFor(modelItem => #Model.LastName)
should be
#Html.ValidationMessageFor(modelItem => modelItem.LastName)
for all your HtmlHelpers, including TextBoxFor and LabelFor etc.
Also
public ActionResult Register(FormCollection formData)
should be
public ActionResult Register(RegisterViewModel model)
in order for your server side ModelState.IsValid to work.
$(document).ready(function () {
$(".ChkBooks").click(function () {
var chkslst = $(".ChkBooks");
var CheckedList = "";
debugger;
$.each(chkslst, function (index, data) {
if (data.checked) {
CheckedList += data.value + ",";
}
});
$("#BookNames").val(CheckedList);
});
});
[Key]
public int Eno { get; set; }
[DisplayName("Employee Name")]
[Required(ErrorMessage = "Name is required")]
[RegularExpression(#"^[a-zA-Z]+$",ErrorMessage = "Pls Enter Only Charaters")]
[StringLength(100, MinimumLength = 3,ErrorMessage = "Name Length Minimun 3 is required")]
public string Ename { get; set; }
[DisplayName("Employee salary")]
//[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:c}")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[Required(ErrorMessage = "salary is required")]
[Range(3000, 10000000, ErrorMessage = "Salary must be between 3000 and 10000000")]
public int salary { get; set; }
[DisplayName("Image")]
[Required(ErrorMessage = "Image is required")]
public HttpPostedFileBase Image { get; set; }
[DisplayName("Email")]
[Required(ErrorMessage = "Email is required")]
[RegularExpression(#"^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$", ErrorMessage ="Please Enter Valid EmailID")]
public string Email { get; set; }
[DisplayName("Password")]
[Required(ErrorMessage = "Password is required")]
[DataType(DataType.Password)]
public string Password { get; set; }
[DisplayName("ConfirmPassword")]
[Required(ErrorMessage = "Password is required")]
[Compare("Password", ErrorMessage = "Password is Not Matching")]
public string ConfirmPassword { get; set; }
[DisplayName("PHONENumber")]
[Required(ErrorMessage = "PhoneNmber is required")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[StringLength(10,ErrorMessage ="maxlimit 10")]
public string PhoneNmber { get; set; }
[DisplayName("Age")]
[RegularExpression(#"^[0-9]*$", ErrorMessage = "Pls Enter Only Numbers")]
[Required(ErrorMessage = "Age is required")]
public int Age { set; get; }
[DisplayName("Gender")]
[Required(ErrorMessage = "Gender is required")]
public bool Gender { get; set; }
[DisplayName("Date")]
[Required(ErrorMessage = "Date is required")]
public DateTime DateandTime { get; set; }
[DisplayName("BookNames")]
[Required(ErrorMessage = "Date is required")]
public List<string> BookNames { get; set; }
}
#{
ViewBag.Title = "Registration";
List<Books> BooksLists = (List<Books>)ViewBag.BooksList;
}
<h2>Registration</h2>
#*#using (Html.BeginForm())*#
#using (Html.BeginForm("Registration", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employees</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Ename, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Ename, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Ename, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.salary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.salary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.salary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Image, new { #type = "file", #accept = "image/x-png,image/gif,image/jpeg" }) #*image/**#
#Html.ValidationMessageFor(model => model.Image, "", 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.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">
#Html.LabelFor(model => model.PhoneNmber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.PhoneNmber, new { htmlAttributes = new { #class = "form-control" } })*#
#Html.TextBoxFor(model => model.PhoneNmber, "{0:c}", new { #class = "required numeric", id = "CurrentBalance" })
#Html.ValidationMessageFor(model => model.PhoneNmber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#*#Html.RadioButtonFor(m => m.Gender, "true") <label> Male </label>
#Html.RadioButtonFor(m => m.Gender, "false") <label> Female </label>*#
#Html.DropDownListFor(model => model.Gender, new SelectList(new List<Object>{
new { value = "" , text = "Select" },
new { value = 1 , text = "Male" },
new { value = 0 , text = "Female"} }, "value", "text", 0))
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateandTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateandTime, new { htmlAttributes = new { #class = "form-control", #type = "date" } })
#Html.ValidationMessageFor(model => model.DateandTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BookNames, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#if (Model != null)
{
for (int i = 0; i < #BooksLists.Count; i++)
{
#Html.CheckBox(Convert.ToString(#BooksLists[i].BookName), false, new { #class = "ChkBooks", style = "margin-left: 20px;vertical-align: 1px;width: 16px;height: 16px; ", #type = "checkbox", #value = Convert.ToString(#BooksLists[i].BookId) })
#BooksLists[i].BookName;
}
}
else
{
for (int i = 0; i < #BooksLists.Count(); i++)
{
#Html.CheckBox(Convert.ToString(BooksLists[i].BookName), false, new { #class = "ChkBooks", style = "margin-left: 20px;vertical-align: 1px;width: 16px;height: 16px; ", #type = "checkbox", #value = Convert.ToString(#BooksLists[i].BookId) })
#BooksLists[i].BookName;
}
}
<br />
#Html.TextBoxFor(m => m.BookNames, new { #class = "form-control", style = "display: none",#readonly = true })
#Html.ValidationMessageFor(model => model.BookNames, "", 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>

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

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

Categories

Resources