Update decimal numbers when using other local - validation

I have this Model
public class SalesModelView
{
[Key]
public int SaleId { get; set; }
public int ShopId { get; set; }
public string ShopName { get; set; }
[Display(Name = "Date")]
public DateTime SaleDate { get; set; }
[Required]
[Display(Name = "Timer")]
[Range(0, 24)]
public int Hours { get; set; }
[Required]
[Display(Name = "Salg")]
public Decimal Sales { get; set; }
[Required]
[Display(Name = "Behandlinger")]
public Decimal Treatments { get; set; }
[Display(Name = "Omsætning")]
public Decimal Turnover { get; set; }
[Display(Name = "Oms./Timer")]
public Decimal TurnoverHour { get; set; }
[Display(Name = "Effektivitet")]
public Decimal Efficiency { get; set; }
}
and in Danish locale a decimal normally shows as 280.800,00, so . as thousands and ,as decimal place.
My view shows the correct stuff
But when saving back to my model, I get the . as a decimal separator, passing all the values to:
(original image for better visualization)
So the number 546.400 is converted to 546,4
I already tried with no luck to hook up the form submit and replace all . with nothing, like
$("form").bind("submit", function() {
$(".number").each(function(){
var v = $(this).val(v).replace('.','');
$(this).val(v);
});
});
What technique do you guys use for this kinda things?
P.S. I did read Hanselman's article but I still got the exact same problems, it's when I pass it to the Controller that goes wrong, all is well in the View

The DefaultModelBinder doesn't work well in these situations. You could write your own or make sure to submit en-US values. Here is an article talking about it.
Model Binding Decimal Values

Related

MVC 5 Conditional Validation

Once again plethora of similar questions and none I can find to help me, or one I can understand.
My struggle is very simple actually. In a register form , I need to validate a few fields IF country selected from a drop down is a specific one. If not , no additional validations are needed. Let's say the country code needs to be "XX" in order to check the fields for things like length, integer or not etc.
I'm very new to MVC (less than a week) and after working with Webforms for a while, even something this simple confuses me. Anyway, here my code pieces
RegisterViewModel(only relevant fields included)
public class RegisterViewModel
{
//
[Required]
[Display(Name="Ülke")]
public string CountryCode {get; set;}
//
//[RegularExpression(#"^[0-9]*$")]
[Required]
[Display(Name = "Posta Kodu")]
public string PostCode { get; set; }
[Required]
[EmailAddress]
[Display(Name = "İrtibat E-Mail Adresi")]
public string Email { get; set; }
//regular expression and string length validations should work only if a certain country is selected
[Required]
[RegularExpression(#"^[0-9]*$")]
[StringLength(11, MinimumLength = 8, ErrorMessage = "Vergi Numarası hatalı.<br/> Lütfen kontrol ediniz.")]
[Display(Name = "Vergi No")]
public string TaxIdNo { get; set; }
//
[Required]
[Display(Name = "Firma Yetkilisi T.C. Kimlik Numarası")]
public string UserCitizenIdNo { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Firma Yetkilisi Email")]
public string UserEmail { get; set; }
[Required]
[Display(Name = "Firma Yetkilisi Tel. No.")]
public string UserPhoneNumber { get; set; }
//
}
The country dropdown
#Html.Bootstrap().DropDownListFor(t => t.CountryCode, MVCUtility.DataTableToListItem((DataTable)ViewBag.CountryList, "Code", "Name")).HtmlAttributes(new { #style = "width:100%;" })
I came across HasSelfValidation on a question but sadly noticed it is retired. How can I make these work inside an if-like construct?
PS: We set the dropdown to a specific value, I need to check if it's changed or not too.

Invalid Column Name Entity guessing a foreign key that isn't there

I don't really understand what's happening here. From my research I gather that entity is trying to guess the name of a foreign key and it's not there, so it's throwing an "Invalid Column Name" error. The problem is that the model/table in question does not have any foreign keys. So I'm really confused.
Here's the code that throws the error:
foreach (TechnologyProjectPlanModel result in results)
{
//get approvers for plan
int id = result.Id;
try
{
List<ApprovalModel> approvers = db.ApprovalModels.Where(m => m.FormId == result.Id).Select(m => m).ToList(); //ERROR HERE
if (approvers != null)
{
result.Approvers = approvers.ToList();
}
}
catch (Exception e)
{
}
}
Here's the ApprovalModel:
public class ApprovalModel
{
[Key]
public int Id { get; set; }
public int ApprovalProcessId { get; set; }
public int FormId { get; set; }
public int UserId { get; set; }
public bool? Approved { get; set; }
}
And here's the TechnologyProjectPlanModel referenced in the foreach loop:
public class TechnologyProjectPlanModel
{
[Key]
public int Id { get; set; }
public int FormId { get; set; }
public int UserId { get; set; }
public string FormType { get; set; }
public int Status { get; set; }
public int Hidden { get; set; }
public DateTime DateSubmitted { get; set; }
public DateTime DateFinalized { get; set; }
public List<QuoteUploadsModel> Quotes { get; set; }
public List<ApprovalModel> Approvers { get; set; }
[Required]
[Display(Name = "Please Select Your School")]
public string School { get; set; }
[Required]
[Display(Name = "Requestor")]
public string Requestor { get; set; }
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Phone Number")]
[Phone]
public string PhoneNumber { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email Address")]
[EmailAddress]
public string Email { get; set; }
[Required]
[Display(Name = "Project Title")]
public string ProjectTitle { get; set; }
[Display(Name = "Requested Completion Date")]
public DateTime RequestedCompletionDate { get; set; }
[Required]
[Display(Name = "Project Description")]
public string ProjectDescription { get; set; }
[Display(Name = "Teacher/Room Number")]
public string TeacherGroup { get; set; }
[Display(Name = "1")]
public bool Grade1 { get; set; }
[Display(Name = "2")]
public bool Grade2 { get; set; }
[Display(Name = "3")]
public bool Grade3 { get; set; }
[Display(Name = "4")]
public bool Grade4 { get; set; }
[Display(Name = "5")]
public bool Grade5 { get; set; }
[Display(Name = "6")]
public bool Grade6 { get; set; }
[Display(Name = "7")]
public bool Grade7 { get; set; }
[Display(Name = "8")]
public bool Grade8 { get; set; }
[Display(Name = "9")]
public bool Grade9 { get; set; }
[Display(Name = "10")]
public bool Grade10 { get; set; }
[Display(Name = "11")]
public bool Grade11 { get; set; }
[Display(Name = "12")]
public bool Grade12 { get; set; }
[Display(Name = "Kindergarten")]
public bool Kindergarten { get; set; }
[Display(Name = "Describe how this plan will be continued if events cause programs or equipment to no longer be available. For example, if equipment purchased needs repair what funding source will be used for repair or replacement? For programs that have annual subscription fees, what funds will be used to continue the program from year to year?")]
public string Sustainability { get; set; }
public bool MultipleFundingSource { get; set; }
[Required(ErrorMessage="*")]
[Display(Name = "Funding Source")]
public string FundingSource1 { get; set; }
[Required(ErrorMessage = "*")]
public string FundingSource2 { get; set; }
[Required(ErrorMessage = "*")]
public string FundingSource3 { get; set; }
[Required(ErrorMessage = "*")]
public string FundingSource4 { get; set; }
[Required(ErrorMessage = "*")]
public string FundingSource5 { get; set; }
[Required]
[Display(Name = "Total Estimated Project Costs:")]
public float TotalEstimatedProjectCosts { get; set; }
//----------------------Additional Information
[Display(Name = "Additional Comments:")]
public string AdditionalComments { get; set; }
[Display(Name = "Additional Supporting Documents:")]
public string AdditionalSupportingDocuments { get; set; }
}
The exact error is:
An error occurred while executing the command definition. See the inner exception for details.
Inner Exception:
Invalid column name 'TechnologyProjectPlanModel_Id'.
That column name isn't referenced anywhere in my code, so it must be inferring it from something.
Any ideas? Thanks!
Entity Framework relies on conventions to determine what it thinks your DB looks like. In this case, it thinks the ApprovalModel table should have a foreign key to the TechnologyProjectPlanModel table. Trimming down your entities to the relevant fields, it becomes apparent why it thinks this:
public class ApprovalModel
{
}
public class TechnologyProjectPlanModel
{
public List<ApprovalModel> Approvers { get; set; }
}
In database terms, the relationship that would most likely exist in order for there to be multiple ApprovalModel's per TechnologyProjectPlanModel would be for ApprovalModel's to have a foreign key to TechnologyProjectPlanModel's.
How does TechnologyProjectPlanModel.Approvers get set? If it doesn't have anything to do with Entity Framework and you don't want it to try populating this property via it's conventions, you can explicitly tell it not to make that assumption by telling it the property is not mapped like so:
[NotMapped]
public List<ApprovalModel> Approvers { get; set; }
If you do have this relationship, you need to give EF some more context so it doesn't make best guess assumptions. For example, if the foreign key does exist, place it in ApprovalModel along with the relevant navigation property that can further tell EF what your DB looks like:
public class ApprovalModel
{
public int TechnologyProjectPlanModelId { get; set; }
// ForeignKey attribute usually not necessary unless you need to tell EF
// about a property that doesn't follow the usual "{OtherEntityName}Id"
// naming convention.
[ForeignKey("TechnologyProjectPlanModelId")]
public TechnologyProjectPlanModel TechnologyProjectPlanModel { get; set; }
}
public class TechnologyProjectPlanModel
{
public List<ApprovalModel> Approvers { get; set; }
}
You know if you do the mapping correctly, that block of code is unnecessary because EF will retrieve results.Approvers for you.
You can use the Attribute based mapping directly on your model or you can use the Code First Configuration to map your foreign key properly.
Once you've properly mapped the foreign key, the block of code you pasted is unnecessary, EF does the load for you.

Model Validation for Date in ASP.NET MVC3 Razor

In my ASP.Net mvc3 Razor project i have to implement date validation.My format for the same was dd-mm-yyyy.i tried in different way but none works fine .I need a simple one.My question is is there any regular expression for the same.
My Model Code
{
[Table("tbl_Employee")]
public class Employee
{
[Key]public int EmpId { get; set; }
[Required(ErrorMessage="Employee First Name is Required")]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required(ErrorMessage="Employee Last Name is Required")]
public string LastName { get; set; }
public int Age{get;set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfBirth { get; set; }
public string Address { get; set; }
public string Position { get; set; }
public string Department { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime DateOfJoining { get; set; }
public string EducationalQuali { get; set; }
public string Experience { get; set; }
public string Others { get; set; }
}
View Code
<div class="col-lg-10" >#Html.TextBoxFor(model => model.DateOfBirth, new { #class = "form-control", placeholder = "Date/Month/Year" })</div>
I have used one placeholder to show the user that ""this was the format".But it is also creating problem from the user.how to solve this?
You can decorate the model property with RegularExpression Attribute Class with the following pattern,
^(0[1-9]|[12][0-9]|3[01])[- /](0[1-9]|1[012])[- /](19|20)[0-9][0-9]$
It will validate following date formats,
dd/MM/yyyy
dd-MM-yyyy
The property value will be set valid if it satisfies the pattern. You can set the custom error message in ErrorMessage property.
[RegularExpression("^(0[1-9]|[12][0-9]|3[01])[- /](0[1-9]|1[012])[- /](19|20)[0-9][0-9]$", ErrorMessage="")]
public DateTime DateOfBirth { get; set; }
This works well on both server and client side. For client side which is better for good user experience, do not forget to turn on the unobtrusive validation and include jquery.validation.js and jquery.validation.unobtrusive.js in your web page. :)

update modelobject in a controller

I am trying to update user in my model object
public ActionResult AddJob(JobQueue job,HttpPostedFileBase file)
{
job.User = "itdev";
TryUpdateModel(job)
if (ModelState.IsValid)//Always returns false
{
}
}
MODEL
public class JobQueue {
[Required]
[Display(Name="JobId")]
public string JobId { get; set; }
[Required] [Display(Name = "FileName")]
public string FileName { get; set; }
[Required]
[Display(Name = "Job Run Date")]
public DateTime JobRunDate { get; set; }
[Required]
[Display(Name = "Email")]
public string Mail { get; set; }
[Required]
[Display(Name = "User")]
public string User { get; set; }
I tried using TryUpdateModel(job) and UpdateModel(job) after assigning the values.Both of these does not seem to update the model because ModelState.IsValid return false.Can someone point me in the right directions?I am using MVC3
Thanks,
Sab
I may be wrong here, but I think job.User = "itdev"; should be sufficent to update the model without using the TryUpdateModel(job) thats how we do it in our site anyway. I have never need to use any method to actually update the model itself. Just assigned values manually.
It depends on how your model is setup I guess.
You should probably post the code for your model just in case my answer isnt helpful.

ASP.Net MVC 3 AutoMapper

I am developing an ASP.Net MVC 3 Web application using Entity Framework 4.1 and also Automapper to map properties from my Objects to ViewModels and vice-versa.
I have the following class called Shift
public partial class Shift
{
public Shift()
{
this.Locations = new HashSet<ShiftLocation>();
}
public int shiftID { get; set; }
public string shiftTitle { get; set; }
public System.DateTime startDate { get; set; }
public System.DateTime endDate { get; set; }
public string shiftDetails { get; set; }
public virtual ICollection<ShiftLocation> Locations { get; set; }
}
And a ViewModel called ViewModelShift
public class ViewModelShift
{
public int shiftID { get; set; }
[DisplayName("Shift Title")]
[Required(ErrorMessage = "Please enter a Shift Title")]
public string shiftTitle { get; set; }
[DisplayName("Start Date")]
[Required(ErrorMessage = "Please select a Shift Start Date")]
public DateTime startDate { get; set; }
[DisplayName("End Date")]
[Required(ErrorMessage = "Please select a Shift End Date")]
public DateTime endDate { get; set; }
[DisplayName("Shift Details")]
[Required(ErrorMessage = "Please enter detail about the Shift")]
public string shiftDetails { get; set; }
[DisplayName("Shift location")]
[Required(ErrorMessage = "Please select a Shift Location")]
public int locationID { get; set; }
public SelectList LocationList { get; set; }
}
I then have the following code in a Controller
[HttpPost]
public ActionResult EditShift(ViewModelShift model)
{
if (ModelState.IsValid)
{
Shift shift = _shiftService.GetShiftByID(model.shiftID);
shift = Mapper.Map<ViewModelShift, Shift>(model);
}
}
Which works fine, when the variable 'shift' is first populated with Shift details, lazy loading also loads the related collection of 'Locations'.
However, once the mapping has taken place, shift.Locations then equals to 0. Is there anyway to setup AutoMapper, that it just maps over the properties in the ViewModel class to the shift without removing the collection of Locations?
Thanks as ever everyone.
Automapper has the ability to designate options for specific members of a created map.
https://github.com/AutoMapper/AutoMapper/wiki/Configuration-validation
Try this:
Mapper.CreateMap<ViewModelShift, Shift>()
.ForMember(dest => dest.Locations, opt => opt.Ignore());

Resources