modelstate.isvalid not getting all the errors - asp.net-mvc

I have this model :
[Required(ErrorMessage = "Please provide a valid EmailAddress")]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Please provide a company name")]
[Display(Name = "Company")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "Please provide a username")]
[Display(Name = "Username")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please select at least one language")]
public int[] SelectedLanguages { get; set; }
[Required(ErrorMessage = "Please select at least one business unit")]
public int[] SelectedBusinessUnits { get; set; }
Now when I do a post from my form using this model and I don't provide any of the values, I only get errormessages for Email, Company and UserName.
I don't get messages for the SelectedLanguages or the SelectedBusinessUnits.
What am i doing wrong?
THis is the view
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.CompanyName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.CompanyName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#foreach (var la in Model.Languages)
{
<input type="checkbox"
name="SelectedLanguages" value="#la.Id" id="#la.Id" />
<label for="#la">#la.Title</label>
}
</div>
<div class="form-group">
#foreach (var bu in Model.BusinessUnits)
{
<input type="checkbox"
name="SelectedBusinessUnits" value="#bu.Id" id="#bu.Id" />
<label for="#bu.Id">#bu.Title</label>
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}

I think you have to go the way of writing a custom validation routine accompanied with a ValidationAttribute. Don't think a simple "out-of-the-box" validator exists for checking if one or more values are present in an array.
Check out this SO post to point you in the right direction.
Basic setup:
public class ArrayContainsValueAttribute: ValidationAttribute
{
// your checks here (pseudo)
if(!array.Any())
return false;
return true;
}
[ArrayContainsValue(ErrorMessage = "Please select at least one business unit")]
public int[] SelectedBusinessUnits { get; set; }

Related

Display name of Identity User who created and last updated record when ID is saved

I must not be searching with the correct phrases. This is a simple concept and I’ve done it in other languages and frameworks with ease.
I’m saving the UserID for the person who created the record and the UserID who last updated the record. Instead of displaying the UserID, I want to display the User.FirstName + ‘ ‘ + User.LastName.
The way I have it currently the LastEditBy and CreateBy is displayed on the page as blank.
Controller: I get the customer model and manually map the model to the customerViewModel then pass it to my partial view.
public ActionResult Edit(int customerId)
{
Customer customer = DbContext.Customers.FirstOrDefault(x => x.CustomerId == customerId);
CustomerViewModel customerViewModel = MapToViewModel(customer);
customerViewModel.UserSelectList = GetUserGroupList();
UserManager<ApplicationUser> _userManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>();
var CreateByUser = _userManager.FindById(customerViewModel.CreateById);
var EditByUser = _userManager.FindById(customerViewModel.LastEditById);
customerViewModel.CreateBy = CreateByUser.FirstName + " " + CreateByUser.LastName;
customerViewModel.LastEditBy = EditByUser.FirstName + " " + EditByUser.LastName;
if (Request.IsAjaxRequest()) {
return PartialView("_CustomerEditPartial", customerViewModel);
}
return View("_CustomerEditPartial", customerViewModel);
}
The CustomerViewModel:
public class CustomerViewModel : DbContext{
public CustomerViewModel(): base("name=CustomerViewModel")
{
}
[Key]
public int CustomerId { get; set; }
[MaxLength(128), ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public SelectList UserSelectList { get; set; }
#region additional Fields
// This overrides default conventions or data annotations
[Required(ErrorMessage = "Please enter your first name.")]
[StringLength(50)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your last name.")]
[StringLength(100)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime CreateDate { get; set; } = DateTime.Now;
public string CreateById { get; set; }
[NotMapped]
public string CreateBy { get; set; }
public string LastEditById { get; set; }
[NotMapped]
public string LastEditBy { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime LastEditDate { get; set; } = DateTime.Now;
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class UserGroupList
{
public string Value { get; set; }
public string Text { get; set; }
}
My partial view page: _CustomerEditPartial.cshtml
#model WOA.ViewModels.CustomerViewModel
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" daa-dismiss="modal" aria-hidden="True">x</button>
<h4 class="modal-title">Edit Customer</h4>
</div>
#using (Ajax.BeginForm("Edit", "Customers", null, new AjaxOptions { HttpMethod = "Post", OnFailure = "OnFail" }, new { #class = "form-horizontal", role = "form" })) {
<div class="modal-body">
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.CustomerId)
<div class="form-group">
#Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.UserId, ViewData.Model.UserSelectList, "Select One", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreateDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CreateDate, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreateBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CreateBy, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastEditBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.LastEditBy, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastEditDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.LastEditDate, new { #readonly = "readonly" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save changes" />
</div>
</div>
</div>
<script type="text/javascript">
function OnSuccess() {
alert("success");
}
function OnFail() {
alert("fail");
}
function OnComplete() {
alert("Complete");
}
</script>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I have updated my code, it is working now, however I do not believe it is the proper way to do this.
I believe I should be able to return the additional values I need via Linq on the initial call and not make two more trips to the database for the additional values.
I have not been able to figure out a way to make this work with Linq.
Thank you in advance for your time and effort.

Data Annotations In mvc

I'm trying to use Data Annotations in my MVC project.
I've created my model and added all the appropriate annotations. I have my view and controller and tried so many ways but i didn't get any result.
When I click on the submit button the validation fired but error messaged not displaying to resolve it.
Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace AllExamples.DTO
{
public class EmployeeViewModel
{
public List<EmployeeInfo> objemployeeinfoList { get; set; }
public EmployeeInfo objemployeeinfo { get; set; }
}
public class EmployeeInfo
{
public int EmployeeID { get; set; }
[Display(Name = "Employee name")]
[Required (ErrorMessage ="Employee name required.")]
public string EmployeeName { get; set; }
[Required(ErrorMessage = "Email id required.")]
public string EmailID { get; set; }
[Required(ErrorMessage = "Contact Number required.")]
public string ContactNumber { get; set; }
public string Department { get; set; }
public string EmployeeType { get; set; }
public string Roles { get; set; }
}
public class BillingInfo
{
public int BillingID { get; set; }
public string BillingName { get; set; }
}
public class NonBillingInfo
{
public int nonbillingId { get; set; }
public string Nonbillingname { get; set; }
}
}
Index.cshtml
#model AllExamples.DTO.EmployeeViewModel
#{
ViewBag.Title = "Home Page";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#*#Html.AntiForgeryToken()*#
#Html.ValidationSummary(false)
<div class="form-group">
#Html.Label("Employee Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.objemployeeinfo.EmployeeName, new { #class = "form-control", Name = "EmployeeName" })
#Html.ValidationMessageFor(m => m.objemployeeinfo.EmployeeName)
</div>
</div>
<div class="form-group">
#Html.Label("Email ID", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.objemployeeinfo.EmailID, new { #class = "form-control",Name= "EmailID" })
#Html.ValidationMessageFor(m => m.objemployeeinfo.EmailID)
</div>
</div>
<div class="form-group">
#Html.Label("Contact Number", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.objemployeeinfo.ContactNumber, new { #class = "form-control", Name = "ContactNumber" })
#Html.ValidationMessageFor(m => m.objemployeeinfo.ContactNumber)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Save" />
</div>
</div>
}
web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Can any one please help how to resolve this issue im not getting what i have missed?
Since you are using a single employee info you don't have to use EmployeeViewModel instead you can use EmployeeInfo and pass the same from controller to view.
Change(View):
#model AllExamples.DTO.EmployeeInfo
#{
ViewBag.Title = "Home Page";
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#*#Html.AntiForgeryToken()*#
#Html.ValidationSummary(false)
<div class="form-group">
#Html.Label("Employee Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.EmployeeName, new { #class = "form-control", Name = "EmployeeName" })
#Html.ValidationMessageFor(m => m.EmployeeName)
</div>
</div>
<div class="form-group">
#Html.Label("Email ID", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.EmailID, new { #class = "form-control",Name= "EmailID" })
#Html.ValidationMessageFor(m => m.EmailID)
</div>
</div>
<div class="form-group">
#Html.Label("Contact Number", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.ContactNumber, new { #class = "form-control", Name = "ContactNumber" })
#Html.ValidationMessageFor(m => m.ContactNumber)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Save" />
</div>
</div>
}
Probably you are not using ModelState.IsValid in you code after post. Try it as
public ActionResult ControllerName(EmployeeInfo obj)
{
if (ModelState.IsValid)
{
//// Your Code
}
}

How to save to database Client IP Address of Visitors Machine in ASP.Net MVC?

am trying to get IP Address of client Machine Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; it's working fine.
Get IP On page load
public ActionResult AddCompany()
{
get_IP();
return View();
}
get_IP code
public void get_IP()
{
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = Request.ServerVariables["REMOTE_ADDR"];
}
ViewBag.IPAddress = ipAddress;
}
But when user register the form get IP address value also save in the data base..
Cs.html File
<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
<h1 class="page-header">Add Company</h1>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.IPAddress)
<div class="form-group">
#Html.LabelFor(model => model.CompanyName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CompanyName)
#Html.ValidationMessageFor(model => model.CompanyName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ShortName, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ShortName)
#Html.ValidationMessageFor(model => model.ShortName)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email)
#Html.ValidationMessageFor(model => model.Email)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Country, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.EditorFor(model => model.Country)*#
#Html.DropDownList("Country", null, "---Select Country----")
#Html.ValidationMessageFor(model => model.Country)
</div>
</div>
<div class="form-group">
<b>State: </b>
<select id="state"></select><br />
</div>
<div>
<b>City: </b>
<select id="city"></select><br />
</div>
<div class="form-group">
#Html.LabelFor(model => model.MobileNo, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MobileNo)
#Html.ValidationMessageFor(model => model.MobileNo)
</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>
</div>
I create one #Html.HiddenFor(model => model.IPAddress) hidden filed value but it's not working ..
On page load IPAddress Value is showing .after i click to save button the Ip value is not saved to the database..
AddCompany
[HttpPost]
public ActionResult AddCompany(Company cmp)
{
using (DataContext entities = new DataContext())
{
entities.Company.Add(cmp);
entities.SaveChanges();
int id = cmp.CompanyID;
Session.Clear();
Response.Redirect("Index");
}
return View(cmp);
}
Any idea How to save client IP Adrress from the database..
Class File
[Table("MySecondMVCDemo")]
public class Company
{
[Key]
public int CompanyID { get; set; }
[Required(ErrorMessage = "Please Enter Company Name")]
[Display(Name = "CompanyName")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "Please Enter Short Name")]
[Display(Name = "ShortName")]
public string ShortName { get; set; }
[Required(ErrorMessage = "Please Enter Email Address")]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Please Enter Email Address")]
[Display(Name = "Country")]
public string Country { get; set; }
[Required(ErrorMessage = "Please Enter Mobile No")]
[Display(Name = "MobileNo")]
public string MobileNo { get; set; }
public Int32? IPAddress { get; set; }
}
I do not know about HiddenFor because I have not use it before.
How I hid fields before was like this:
#Html.TextBoxFor(model => model.IPAddress, new { #class = "sr-only", #type = "hidden" })
You can add the bootstrap class sr-only to make sure it is hidden.
Make sure you check your browser inspector to see whether the hidden field has a value.
If posted and is still not saving, then try to assign the IpAddress identity to the form field value before saving it like this:
cmp.IPAddress = Request.Form["IPAddress"];
Store IP address as a string instead of Int32
Please use code from here to get IP Address
http://tutorialgenius.blogspot.in/2010/09/aspnet-get-ipv4-address-even-if-user-is.html

Bind Checkboxlist to model

I'm working on an app for a cycling team. I have to add riders to a ride. To do this I want the user te select the date of a ride, select a value for the point of this ride an then have a list of the members of the team where the user selects which member participated on the ride.
It works fine until I post the form. when I debug my model in the controler the list of Riders in de model counts 4 riders (which is correct as I have 4 riders in my Db for testing) but the riders are null when I check the list.
Can anyone help me, I dont know what I'm doing wrong.
this are the viewmodels I use:
public class RiderViewModel
{
public string Id { get; set; }
public string FulllName { get; set; }
public bool IsChecked { get; set; }
}
public class RideViewModel
{
public string RideId { get; set; }
[Display(Name = "Datum")]
[DataType(DataType.Date)]
[Required(ErrorMessage = "Datum is verplicht")]
public DateTime Date { get; set; }
[Display(Name = "Aantal punten")]
[Required(ErrorMessage = "Een waarde voor het puntenaantal is verplicht")]
public int Punten { get; set; }
[Display(Name = "Leden")]
public List<RiderViewModel> Riders { get; set; }
}
this is my controler:
//POST Rides/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(RideViewModel model)
{
if (ModelState.IsValid)
{
var db = new ApplicationDbContext();
var riders = new List<ApplicationUser>();
foreach(RiderViewModel r in model.Riders)
{
var user = db.Users.FirstOrDefault(u => u.Id == r.Id);
if(user == null)
{
ModelState.AddModelError(string.Empty, "Er is een Fout opgetreden bij het selecteren van de leden. contacteer de systeembeheerder indien het probleem blijft bestaan");
return View(model);
}
riders.Add(user);
}
var ride = new Ride
{
Date = model.Date,
Punten = model.Punten,
Riders = riders
};
db.Rides.Add(ride);
db.SaveChanges();
return RedirectToAction("Index", "AdminPanel");
}
return View(model);
}
and this is the view:
using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Ride</h4>
<hr />
<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.Punten, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Punten, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Punten, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Leden", htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-10">
#for (var i = 0; i < Model.Riders.Count(); i++)
{
<div class="col-md-10">
#Html.HiddenFor(model => model.Riders[i])
#Html.CheckBoxFor(model => model.Riders[i].IsChecked)
#Html.LabelFor(model => model.Riders[i].IsChecked, Model.Riders[i].FulllName)
</div>
}
</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>
}
Thanx a lot.
grtz Jeff
You can use a EditorTemplate for this, just add a new file in the EditorTemplates folder named RiderViewModel :
#model RiderViewModel
<div class="col-md-10">
#Html.HiddenFor(model => model.Id)
#Html.CheckBoxFor(model => model.IsChecked)
#Html.LabelFor(model => model.IsChecked, Model.FulllName)
</div>
Then in the view just call the EditorFor:
#Html.EditorFor(m => m.Riders)
Your usage of
#Html.HiddenFor(model => model.Riders[i])
is creating a hidden input for a complex property which is typeof RiderViewModel. If you inspect the html, it will be something like
<input type="hidden" id="Riders_0_" name="Riders[0]" value="someAssembly.RiderViewModel" />
When you submit, the DefaultModelBinder tries to set model.Riders[0] to the value someAssembly.RiderViewModel which fails and so model.Riders[0] is null
Assuming you want to generate a hidden input for the ID property, change it to
#Html.HiddenFor(model => model.Riders[i].ID)

Error while inserting floating point value in textboxfor MVC

I have a strange problem, I have a model definied like this:
public class AddEventModel
{
[Required]
[DataType(DataType.Text)]
[Display(Name = "Nazwa wydarzenia")]
public string EventName { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Rodzaj")]
public string EventType { get; set; }
[Required]
[DataType(DataType.DateTime)]
[Display(Name = "Data")]
public System.DateTime EventDate { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Widocznosc")]
public string IsPublic { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Minimalny wiek")]
public int MinimalAge { get; set; }
[Display(Name = "Cena")]
[DataType(DataType.Text)]
public decimal Payment { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Opis")]
public string Description { get; set; }
[Required]
[DataType(DataType.Text)]
[Display(Name = "Miasto")]
public string City { get; set; }
public SelectList EventTypeList { get; set; }
}
What is more i have a page writen in razor like this (i will post just part of it):
<div class="form-group">
#Html.LabelFor(m => m.EventName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.EventName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.EventType, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.EventType, Model.EventTypeList, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.EventDate, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.EventDate, new { #class = "form-control", id = "datepicker" })
</div>
<script type="text/javascript">
$(function () {
$('#datepicker').datetimepicker({
minDate: moment()
});
});
</script>
</div>
<div class="form-group">
#Html.LabelFor(m => m.IsPublic, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
<table>
<tr>
<td><label>#Html.RadioButtonFor(m => m.IsPublic, "Prywatne") Prywatne</label></td>
</tr>
<tr>
<td><label>#Html.RadioButtonFor(m => m.IsPublic, "Publiczne") Publiczne</label></td>
</tr>
</table>
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.MinimalAge, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.MinimalAge, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Payment, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Payment, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Description, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextAreaFor(m => m.Description, new { #class = "form-control" })
</div>
</div>
</div>
Okay, so, when I am inserting my new event with a floating point number in field Cena/Payment im getting a strange error like this:
The ViewData item that has the key 'EventType' is of type 'System.String' but must be of type 'IEnumerable'.
It is pretty strange beacuse it is pointing on dropdownlist which is not connected with a Payment field. As I said, when I put a integer into Payment field - everything works fine.
Whats going on guys?
EDIT
Okey guys, i get it that i didnt reassing a SelectList in a post method. I fixed that already. However:
I want to understand why it was apearing only when i put a floating point number in a textbox
How to fix next problem: Value 'x.x' is not valid for Cena
The error is throw because the value of EventTypeList in
#Html.DropDownListFor(m => m.EventType, Model.EventTypeList, new { #class = "form-control" }
is null
This is happening because when you post back, ModelState is invalid and you return the view without re-assigning the SelectList (as you did in the GET method).
The reason ModelState is invalid is because the culture on the server does not accept the . (dot) character as a decimal separator (most likely it is a culture that uses , (comma) as the decimal separator). You need to change the culture in the web.config file, for example to <<globalization culture ="en-US" />

Resources