I have a Userstats model, and a user model, the Modelstate.isvalid in the controller is returning false, I think it may have something to do with the reltionship between the the two models but i'm not sure
userstats model:
public class UserStats
{
Calculator CalculateStats = new Calculator();
public ActivityLevel ActivitySelected { get;set; }
[Key]
public int ID { get; set; }
public User User { get; set; }
[DisplayName("Weight")]
[Required]
public double Weight { get; set; }
[DisplayName("Chest Measurement")]
[Required]
public double ChestMeasurement { get; set; }
[DisplayName("Hip Measurement")]
[Required]
public double HipMeasurement { get; set; }
[DisplayName("Waist Measurement")]
[Required]
public double WaistMeasurement { get; set; }
[DisplayName("Bicep Measurement")]
[Required]
public double BicepMeasurment { get; set; }
[DisplayName("Height Measurement(Inches)")]
[Required]
public double Height { get; set; }
[DisplayName("Body Fat %")]
[NotMapped]
public double BodyFat { get; set; }
[NotMapped]
public double BMI
{
get { return CalculateStats.CalculateBMI(Weight,Height); }
}
[NotMapped]
public double BMR
{
//get { return CalculateStats.CalculateBMR(user.SelectedGender, Weight, Height, user.Age); }
get { return 0; }
}
[DisplayName("Stats Log Date")]
[Required]
public DateTime StatDate { get; set; }
[DisplayName("Target Weight")]
[Required]
public double TargetWeight { get; set; }
[DisplayName("Target Date")]
[Required]
public DateTime TargetDate { get; set; }
[DisplayName("Wrist Measurement(Inches)")]
[Required]
public double WristMeasurement { get; set; }
[DisplayName("Forearm Measurement(Inches)")]
[Required]
public double ForeArm { get; set; }
[DisplayName("Daily Caloric Intake")]
[NotMapped]
public double DailyIntake { get; set; }
[DisplayName("Daily Allowance")]
[NotMapped]
public double DailyCalories { get; set; }
[DisplayName("Lean Body Mass")]
[NotMapped]
public double LeanMass { get; set; }
}
user model:
public class User
{
[Key]
public int ID { get; set; }
public virtual ICollection<UserStats> UserStats { get; set; }
[DisplayName("First Name")]
[Required]
public string FirstName { get; set; }
[DisplayName("Last Name")]
[Required]
public string LastName { get; set; }
[DisplayName("D.O.B")]
[DataType(DataType.Date)]
public DateTime DOB { get; set; }
private int _age;
[NotMapped]
public int Age
{
get { return _age; }
set
{
DateTime today = DateTime.Today;
_age = today.Year - DOB.Year;
if (DOB > today.AddYears(-_age)) _age--;
}
}
[DisplayName("Address")]
public string Address { get; set; }
[Required]
public string Email { get; set; }
[Required]
public Gender Gender { get; set; }
[DisplayName("UserName")]
public string UserName { get; set; }
public Gender SelectedGender { get; set; }
}
}
registeMale controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RegisterMale(User u,UserStats userstats)
{
if (ModelState.IsValid)
{
var user = db.Users.SingleOrDefault(i => i.ID == u.ID);
userstats.User = user;
db.UserStats.Add(userstats);
db.SaveChanges();
return RedirectToAction("Details", "Dashboard", new { id = userstats.ID });
}
return View(userstats);
}
View:
<fieldset>
<legend>UserStats</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Weight)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Weight)
#Html.ValidationMessageFor(model => model.Weight)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ChestMeasurement)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ChestMeasurement)
#Html.ValidationMessageFor(model => model.ChestMeasurement)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HipMeasurement)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HipMeasurement)
#Html.ValidationMessageFor(model => model.HipMeasurement)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.WaistMeasurement)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.WaistMeasurement)
#Html.ValidationMessageFor(model => model.WaistMeasurement)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.BicepMeasurment)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.BicepMeasurment)
#Html.ValidationMessageFor(model => model.BicepMeasurment)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Height)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Height)
#Html.ValidationMessageFor(model => model.Height)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.StatDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.StatDate)
#Html.ValidationMessageFor(model => model.StatDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TargetWeight)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TargetWeight)
#Html.ValidationMessageFor(model => model.TargetWeight)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TargetDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TargetDate)
#Html.ValidationMessageFor(model => model.TargetDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.WristMeasurement)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.WristMeasurement)
#Html.ValidationMessageFor(model => model.WristMeasurement)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ForeArm)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ForeArm)
#Html.ValidationMessageFor(model => model.ForeArm)
</div>
<table>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.Sedentary) Sedentary
</td>
</tr>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.LightActivity) Light Activity
</td>
</tr>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.Moderate) Moderate
</td>
</tr>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.Active) Active
</td>
</tr>
<tr>
<td>
#Html.RadioButtonFor(model => model.ActivitySelected, Fitness_Friend.Web.Enumeration.ActivityLevel.Extra) Extra
</td>
</tr>
</table>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
It seems your models are not connected. There is no same id filed. You may add userID to UserStats. And I think your RegisterMale method expects only one model UserStats. Just rewrite it as follows
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RegisterMale(UserStats model)
{
if (ModelState.IsValid)
{
var user = db.Users.SingleOrDefault(i => i.ID == model.userID );
db.UserStats.Add(userstats);
db.SaveChanges();
return RedirectToAction("Details", "Dashboard", new { id = userstats.ID });
}
return View(userstats);
}
Related
i can't seem to find the answer online...
I have a form where people can add persons. However the person I receive from the post request is empty.
My personModel has a few properties , Naam, Leeftijd and Hobbie.
My Create view has a form made with #Html.LabelFor.
Model:
public class PersoonModel
{
public string Naam { get; private set; }
public int Leeftijd { get; private set; }
public string Hobbie { get; private set; }
public PersoonModel(string naam,int leeftijd, string hobbie )
{
Naam = naam;
Leeftijd = leeftijd;
Hobbie = hobbie;
}
public PersoonModel()
{
}
}
View:
#using (Html.BeginForm("Create","Dashboard",FormMethod.Post))
{
<fieldset>
<legend>Persoon</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Naam)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Naam)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Leeftijd)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Leeftijd)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Hobbie)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Hobbie)
</div>
<input type="submit" value="Create new Person"/>
</fieldset>
Controller:
[HttpGet]
public ActionResult Create()
{
PersoonModel persoonModel = new PersoonModel();
return View(persoonModel);
}
[HttpPost]
public ActionResult Create(PersoonModel Persoon)
{
personen.Add(Persoon);
return Redirect("/Dashboard");
}
I can't seem to get the layout good on stackoverflow, but I hope you understand it
The persoonmodel Persoon(in my Controller) is empty
The problem is that your setters are private and MVC model binder cannot fill-in the private values:
public class PersoonModel
{
// remove private before set
public string Naam { get; set; }
public int Leeftijd { get; set; }
public string Hobbie { get; set; }
// more code...
}
I don't understand why you are using all that code in your model.
I also took the liberty to change the variables to english.
Just use this
The Model
public class PersonModel
{
public string Name { get; set; }
public int PID { get; set; }
public string Hobbie { get; set; }
}
The View
// path to your personModel
#ApplicationName.ModelFolder.PersonModel
#using (Html.BeginForm("Create","Dashboard",FormMethod.Post))
{
<fieldset>
<legend>Person</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PID)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.PID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Hobbie)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Hobbie)
</div>
<input type="submit" value="Create new Person"/>
</fieldset>
}
and the controller
[HttpGet]
public ActionResult Create()
{
PersonModel personModel = new PersonModel();
return View(personModel);
}
[HttpPost]
public ActionResult Create(PersonModel model)
{
personen.Add(model);
return Redirect("/Dashboard");
}
This should get the values on the post function if you debug it.
I have a form and using Grid.MVC to display in same page. When I try run my program, it show error : 'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage.Model'..
Here the sample of my code
This is my model
public class Course
{
[DisplayName("Customer Name")]
public string customer { get; set; }
[DisplayName("Contact")]
public string contact { get; set; }
[UIHint("DropDownList")]
[Required(ErrorMessage = "Please select the package")]
public int CoursePackageID { get; set; }
[Required]
public int CustomerID { get; set; }
[Required(ErrorMessage = "The date is required")]
[DisplayName("Date Of Register")]
public DateTime dtRegister { get; set; }
[DisplayName("Payment")]
public string payment { get; set; }
public List<CourseObject> lCourse { get; set; }
public class CourseObject
{
public int courseId { get; set; }
[DisplayName("Package")]
public string package { get; set; }
[DisplayName("Date Of Register")]
public DateTime date_register { get; set; }
[DisplayName("Payment")]
public string payment { get; set; }
}
}
And this is my CSHTML (Razor)
#model BangiProject.Models.Course
#using GridMvc.Html
#{
ViewBag.Title = "Register";
}
<h2>
Register</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Course</legend>
<div class="control-label">
#Html.LabelFor(model => model.customer)
</div>
<div class="form-control-static">
#Html.DisplayFor(model => model.customer)
</div>
<div class="control-label">
#Html.LabelFor(model => model.contact)
</div>
<div class="form-control-static">
#Html.DisplayFor(model => model.contact)
</div>
<div class="editor-label">
Category :
</div>
<div class="editor-field">
#Html.DropDownListFor(Model => Model.CoursePackageID, new SelectList(ViewBag.CoursePackage as System.Collections.IEnumerable, "id", "course_name", new { #style = "drop-down" }),
"-Choose Package-", new { id = "cat" })
</div>
<div class="editor-label">
#Html.LabelFor(model => model.dtRegister)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.dtRegister)
#Html.ValidationMessageFor(model => model.dtRegister)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.payment)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.payment)
#Html.ValidationMessageFor(model => model.payment)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div class="row">
#Html.Grid(Model.lCourse).Columns(columns =>
{
columns.Add(c => c.courseId).Titled("ID")
.Sanitized(false)
.Encoded(false)
.RenderValueAs(o => Html.ActionLink("Edit", "Edit", "Merchant", new { id = o.courseId }, null).ToHtmlString());
columns.Add(c => c.package).Titled("Package").Filterable(true);
columns.Add(c => c.date_register).Titled("Date Of Register").Filterable(true);
}).WithPaging(25).Sortable(true)
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The error show on this line
#Html.Grid(Model.lCourse).Columns
Please advice...
Usually this means that you're using the reserved "Model" keyword erroneously somewhere. In your case:
#Html.DropDownListFor(Model => Model.CoursePackageID...
Change this to:
#Html.DropDownListFor(model => model.CoursePackageID...
Try changing the line in question as below(lowercase 'm')...
#Html.Grid(model.lCourse).Columns
I have created a strongly typed view using visual studio and have added some dropdownlists for the user to select an option from a connected database table column but these dropdownlists seem to cause some issues. I keep getting the errors below and I am not sure why. These drop downs should be saving the options as a string to corresponding item record. Not sure why it is looking for a key named AssignedTo. Any suggestions? All help is much appreciated.
Error Message:
There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'AssignedTo'.
Source Error:
Line 34: </div>
Line 35: <div class="editor-field">
Line 36: #Html.DropDownListFor(model => model.AssignedTo, (SelectList)ViewBag.AssignedToList)
Line 37: #Html.ValidationMessageFor(model => model.AssignedTo)
Line 38: </div>
Here is my strongly typed Create View:
#model ApIssues.Models.AP_Tasks
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Issue</legend>
<div class="editor-label">
#Html.LabelFor(model => model.TaskDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TaskDate)
#Html.ValidationMessageFor(model => model.TaskDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.InvDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.InvDate)
#Html.ValidationMessageFor(model => model.InvDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AssignedTo)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.AssignedTo, (SelectList)ViewBag.AssignedToList)
#Html.ValidationMessageFor(model => model.AssignedTo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CC)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.CC, (SelectList)ViewBag.CcToList)
#Html.ValidationMessageFor(model => model.CC)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Whse)
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.Whse, (SelectList)ViewBag.WarehouseList)
#Html.ValidationMessageFor(model => model.Whse)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PO)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PO)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FreightNo)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FreightNo)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.VendName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.VendName)
#Html.ValidationMessageFor(model => model.VendName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ReqCompDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ReqCompDate)
#Html.ValidationMessageFor(model => model.ReqCompDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.TaskType)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.TaskType)
#Html.ValidationMessageFor(model => model.TaskType)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Here is my model:
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Validation;
namespace ApIssues.Models
{
using System;
using System.Collections.Generic;
public partial class AP_Tasks
{
[Required]
public int TaskID { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Task Date")]
public Nullable<System.DateTime> TaskDate { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Task Type")]
public string TaskType { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Assigned By")]
public string AssignedBy { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Assigned To")]
public string AssignedTo { get; set; }
[DataType(DataType.Text)]
[Display(Name = "CC")]
public string CC { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Warehouse")]
public string Whse { get; set; }
[DataType(DataType.Text)]
[Display(Name = "PO #")]
public string PO { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Freight #")]
public string FreightNo { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Vendor Name")]
public string VendName { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Req. Complete Date")]
public Nullable<System.DateTime> ReqCompDate { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Due Date")]
public Nullable<System.DateTime> DueDate { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Completion Date")]
public Nullable<System.DateTime> CompDate { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Notes Summary")]
public string Notes { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Invoice Date")]
public Nullable<System.DateTime> InvDate { get; set; }
[Display(Name = "Company Number")]
public Nullable<int> CoNo { get; set; }
[Display(Name = "Note Count")]
public Nullable<int> NoteCnt { get; set; }
}
}
Here is my Action:
[HttpGet]
public ActionResult Create()
{
//TODO: Add drop down lists
//TODO: Change the Cono in Query1
var nxtDb = new nxtSQLEntities();
var whses = from w in nxtDb.icsds select w.whse;
var warehouseList = new SelectList(whses);
ViewBag.WarehouseList =
warehouseList;
var userDb = new PDDAEntities1();
var query1 = from u in userDb.Users where u.Cono == 1 select new {u.UserName, u.FirstName, u.LastName};
var query2 = from gm in userDb.GroupMembers
join ug in userDb.UserGroups on gm.GroupID equals ug.GroupID
join u in userDb.Users on gm.UserName equals u.UserName
where ug.GroupName == "AP Department" || ug.GroupName == "MIS"
orderby new {u.LastName, u.FirstName}
select new {UserName = u.UserName, FirstName = u.FirstName, LastName = u.LastName};
var query3 = query1.Concat(query2);
var results = new List<string>{};
results.AddRange(query3.Select(entry => entry.UserName));
ViewBag.AssignedToList = new SelectList(results);
ViewBag.CcToList = new SelectList(results);
return View();
}
[HttpPost]
public ActionResult Create(AP_Tasks task)
{
// Save an task to the database
var db = new Accounting_AaronTestEntities();
try
{
db.AP_Tasks.Add(task);
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
return View();
}
return RedirectToAction("Index");
}
Anyone know why I am getting this error?
Try it this way.
#Html.DropDownListFor(model => model.AssignedTo,
new SelectList(ViewBag.AssignedToList, "Id", "AssignedTo"), "---Select Assigner---", new { ID = "ddlAssigned" })
Hope it helps.
try variants of the top two answers here:
Having difficulty using an ASP.NET MVC ViewBag and DropDownListfor
I'm trying to get a dropdown menu along side my other text inputs, I've been tracking a music store tutorial for this specific feature, but I cant seem to get mine to work. I've been revising my code and comparing for hours but I cant see my errors, If anyone can help it would be greatly appreciated.
Here is my controller code:
// GET: /Default1/Create
public ActionResult Create()
{
ViewBag.CardTypeId = new SelectList(db.CardTypee, "CardTypeId", "Type");
return View();
}
//
// POST: /Default1/Create
[HttpPost]
public ActionResult Create(Card card)
{
if (ModelState.IsValid)
{
db.Cards.Add(card);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CardTypeId = new SelectList(db.CardTypee, "CardTypeId", "Type", card.CardTypeId);
return View(card);
}
My models that I have:
Card.cs
namespace ActualPayment.Models
{
public class Card
{
public int Id { get; set; }
public CardType CardType { get; set; }
public int CardTypeId { get; set; }
public string Name { get; set; }
public string CardNumber { get; set; }
public int SortCode { get; set; }
public int SecurityCode { get; set; }
public int ExpirationDate { get; set; }
}
}
CardType.cs
namespace ActualPayment.Models
{
public partial class CardType
{
[Key] public int CardTypeId { get; set; }
public string Type { get; set; }
}
}
CardTypes.cs
namespace ActualPayment.Models
{
public class CardTypes : DropCreateDatabaseIfModelChanges<CardPayment>
{
protected override void Seed(CardPayment context)
{
var cardType = new List<CardType>
{
new CardType { Type = "Visa/Delta/Electron" },
new CardType { Type = "Master Card/Euro Card" },
new CardType { Type = "American Express" },
new CardType { Type = "Solo/Maestro" },
new CardType { Type = "Maestro" },
};
}
}
}
CardPayments.cs
namespace ActualPayment.Models
{
public class CardPayment : DbContext
{
public DbSet<CardType> CardTypee { get; set; }
public DbSet<Card> Cards { get; set; }
}
}
And my view:
#model ActualPayment.Models.Card
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"> </script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Card</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CardTypeId, "CardType")
</div>
<div class="editor-field">
#Html.DropDownList("CardTypeId", String.Empty)
#Html.ValidationMessageFor(model => model.CardTypeId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.CardNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.CardNumber)
#Html.ValidationMessageFor(model => model.CardNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SortCode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SortCode)
#Html.ValidationMessageFor(model => model.SortCode)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.SecurityCode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.SecurityCode)
#Html.ValidationMessageFor(model => model.SecurityCode)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ExpirationDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ExpirationDate)
#Html.ValidationMessageFor(model => model.ExpirationDate)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Seems like there's nothing wrong with the code.
Chrome capture for posted values
value at action
Did you mean the CardTypeId is not getting populated??
I am developing an MVC 3 application and I am sending emails using MvcMailer.I am able to send basic emails, but I am trying to email the contents of a form and can't seem to work it out.
Here is the code for my model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace DFPProductions_Default.Models
{
public class Application
{
[Required]
[Display(Name = "First Name")]
public string ApplicantFirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string ApplicantLastName { get; set; }
[Display(Name = "Birth Date")]
public DateTime ApplicantBirthDate { get; set; }
[Required]
[Display(Name = "Cellphone Number")]
public string ApplicantCellphoneNumber { get; set; }
[Display(Name = "Postal Address")]
public string PostalNumber { get; set; }
[Display(Name = "Suburb")]
public string ApplicantSuburb { get; set; }
[Display(Name = "City")]
public string ApplicantCity { get; set; }
[Display(Name = "Post Code")]
public string ApplicationPostalCode { get; set; }
[Required]
[Display(Name = "Email Address")]
public string ApplicantEmailAddress { get; set; }
[Display(Name = "First Name")]
public string ParentFirstName { get; set; }
[Display(Name = "Last Name")]
public string ParentLastName { get; set; }
[Display(Name = "Email Address")]
public string ParentEmailAddress { get; set; }
[Display(Name = "Postal Address")]
public string ParentPostalNumber { get; set; }
[Display(Name = "Suburb")]
public string ParentSuburb { get; set; }
[Display(Name = "City")]
public string ParentCity {get; set;}
[Display(Name = "Post Code")]
public string ParentPostalCode {get; set;}
}
}
In my view, I have editor fields, here are a few:
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantFirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantFirstName)
#Html.ValidationMessageFor(model => model.ApplicantFirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantLastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantLastName)
#Html.ValidationMessageFor(model => model.ApplicantLastName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantBirthDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantBirthDate)
#Html.ValidationMessageFor(model => model.ApplicantBirthDate)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantCellphoneNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantCellphoneNumber)
#Html.ValidationMessageFor(model => model.ApplicantCellphoneNumber)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantEmailAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantEmailAddress)
#Html.ValidationMessageFor(model => model.ApplicantEmailAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.PostalNumber)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.PostalNumber)
#Html.ValidationMessageFor(model => model.ApplicantEmailAddress)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantSuburb)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantSuburb)
#Html.ValidationMessageFor(model => model.ApplicantSuburb)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicantCity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicantCity)
#Html.ValidationMessageFor(model => model.ApplicantCity)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ApplicationPostalCode)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ApplicationPostalCode)
#Html.ValidationMessageFor(model => model.ApplicationPostalCode)
</div>
</div>
I have called the email Application. The code for ApplicationMailer is:
public virtual MailMessage Application()
{
var mailMessage = new MailMessage{Subject = "Application"};
mailMessage.To.Add("debbie#gmail.com");
ViewBag.Data = "Debbie";
PopulateBody(mailMessage, viewName: "Application");
return mailMessage;
}
I have this in my controller:
private IApplicationMailer _applicationMailer = new ApplicationMailer();
public IApplicationMailer ApplicationMailer
{
get { return _applicationMailer; }
set { _applicationMailer = value; }
}
public ActionResult SendApplication()
{
ApplicationMailer.Application().Send();
//Send() extension method: using Mvc.Mailer
return RedirectToAction("Index");
}
And all I've added to the view of the email is
#model DFPProductions_Default.Models.Application
The email sends, so it is configured correctly, but I'm really not sure how to retrieve the values inserted into the form in the email view.
Thanks,
Amy
You need to utilize your model class data in the controller something like this:
public virtual MailMessage Application(ModelNameHere model)
{
var mailMessage = new MailMessage{Subject = "Application"};
mailMessage.To.Add("debbie#gmail.com");
//add field from your view here
string body = model.CellPhoneNumber + Model.FirstName;
ViewBag.Data = "Debbie";
PopulateBody(mailMessage, viewName: "Application", body);
return mailMessage;
}