I'm trying to write a method that generates multiple commission slips. This is for a college, where clients are enrolled with tutors in a class called Enrollments. With this method, I am trying to accumulate the monthly fee of the tutors' clients multiplied by their commission percentages, as tutors earn a certain commission on the lessons they give. Here is my code for this:
public ActionResult CreateBulkCommissions()
{
var month = DateTime.Now.ToString("MMMM");
var enrolments = db.Enrollments.ToList();
var newCommissions = from enrolment in enrolments
select new TutorCommission()
{
CommissionAmount = enrolment.MonthlyFee,
CommissionMonth = month, // string constant
CommissionStatus = "Unpaid",
Tutor = enrolment.Tutor
};
foreach (var newCommission in newCommissions)
{
List<TutorCommission> TutorComs = newCommissions.GroupBy(g => g.Tutor).Select(s => new TutorCommission
{
CommissionAmount = s.Sum(u => u.CommissionAmount) * s.Key.TutorCommissionPercentage,
TutorNoID = s.Key.TutorNoID
}).ToList();
db.TutorCommission.Add(newCommission);
db.SaveChanges();
}
return RedirectToAction("Index");
}
The problem is that TutorCommission entries are created for each individual enrollment, instead of one entry per tutor (for the month) with the total commission amount. I.e. Ashley has 3 clients and therefore 3 enrollments and currently 3 TutorCommission entries are being created for him. I want to add up the enrollments amounts for one entry. In addition, the amount is not being multiplied by the commission percentage, so it is just saving as the full enrollment monthly fee. Relevant classes are:
public class Enrollment
{
[Key]
[Display(Name = "Enrollment ID Number")]
public long EnrollmentIDNumber { get; set; }
[Display(Name = "Client ID Number")]
public long ClientNumberID { get; set; }
[Display(Name = "Tutor ID Number")]
public long TutorNoID { get; set; }
[Display(Name = "Course Name")]
public string CourseName { get; set; }
[Display(Name = "Lesson Time")]
public string LessonTime { get; set; }
[Display(Name = "Lesson Day")]
public string LessonDay { get; set; }
[Display(Name = "Lesson Location")]
public string LessonLocation { get; set; }
[Display(Name = "Lesson Type")]
public string LessonType { get; set; }
[Display(Name = "Lesson Level")]
public string LessonLevel { get; set; }
[Display(Name = "Monthly Fee")]
public long MonthlyFee { get; set; }
public virtual Client Client { get; set; }
public virtual Tutor Tutor { get; set; }
}
public class TutorCommission
{
[Key]
[Display(Name = "Commission ID")]
public long CommissionID { get; set; }
[Display(Name = "Commission Month")]
public string CommissionMonth {get; set;}
[Display(Name = "Commission Amount")]
public double CommissionAmount { get; set; }
[Display(Name = "Commission Status")]
public string CommissionStatus { get; set; }
[Display(Name = "Tutor ID Number")]
public long TutorNoID { get; set; }
public virtual Tutor Tutor { get; set; }
public virtual ICollection<CommissionPayments> CommissionPayments { get; set; }
}
public class Tutor
{
[Key]
[Display(Name = "Tutor ID Number")]
public long TutorNoID { get; set; }
[Required]
[StringLength(50, ErrorMessage="First name must be less than 50 characters")]
[Display(Name = "First Name")]
public string TutorFirstName { get; set; }
[StringLength(50, ErrorMessage = "Last name must be less than 50 characters")]
[Display(Name = "Last Name")]
public string TutorLastName { get; set; }
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
[Display(Name = "Birth Date")]
public DateTime? TutorBirthDate { get; set; }
[Display(Name = "Cellphone Number")]
public string TutorCellphoneNumber { get; set; }
[Display(Name = "Home Number")]
public string TutorHomeNumber { get; set; }
[RegularExpression("^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*#[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$", ErrorMessage = "Not a valid email address")]
[Display(Name = "Email Address")]
public string TutorEmailAddress { get; set; }
[Display(Name = "Street Address")]
public string TutorStreetAddress { get; set; }
[Display(Name = "Suburb")]
public string TutorSuburb { get; set; }
[Display(Name = "City")]
public string TutorCity { get; set; }
[Display(Name = "Postal Code")]
public string TutorPostalCode { get; set; }
[Display(Name="Full Name")]
public string FullName
{
get
{
return TutorFirstName + " " + TutorLastName;
}
}
[Display(Name="Commission Percentage")]
[Required]
public double TutorCommissionPercentage { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
public virtual ICollection<TutorCommission> TutorCommissions { get; set; }
}
Thanks,
Amy
You can try moving the grouping logic outside the foreach loop, then iterating on the grouped list. So instead of
foreach (var newCommission in newCommissions)
{
List<TutorCommission> TutorComs = newCommissions.GroupBy(g => g.Tutor).Select(s => new TutorCommission
{
CommissionAmount = s.Sum(u => u.CommissionAmount) * s.Key.TutorCommissionPercentage,
TutorNoID = s.Key.TutorNoID
}).ToList();
db.TutorCommission.Add(newCommission);
db.SaveChanges();
}
try
List<TutorCommission> TutorComs = newCommissions.GroupBy(g => g.Tutor).Select(s => new TutorCommission
{
CommissionAmount = s.Sum(u => u.CommissionAmount) * s.Key.TutorCommissionPercentage,
TutorNoID = s.Key.TutorNoID
}).ToList();
foreach (var tutorCom in TutorComs)
{
db.TutorCommission.Add(tutorCom);
db.SaveChanges();
}
See if that is closer to the desired result.
Related
I have used this
public List<InspectionReport> GetInspectionReportDetails(int InspectionReportID)
{
var List= this.Database.SqlQuery<InspectionReport>("GetInspectionReportDetails", InspectionReportID).ToList();
return List;
}
in a class that is inherited from DbContext
I am calling this function in a controller but List is empty. Database.SqlQuery returns 0 items even the procedure is returning data for the parameter i am providing to the function but not this.
Update:
alter PROCEDURE GetInspectionReportDetails
#InspectionReportID int=0
AS
BEGIN
Select ir.InspectionReportID
,ir.VelosiProjectNo
,ir.VelosiReportNo
,ir.Reference
,ir.PoNo
,ir.InspectionDate
,ir.IssueDate
,ir.InspectionPhase
,ir.InServiceInspection
,ir.NewInduction
,ir.HydrostaticTest
,ir.DimensionalCheck
,ir.ThicknessCheck
,ir.Patrom
,ir.Gvs
,ir.FinalOgraInspection
,ir.OmcClientRequirement
,ir.TankLorryRegistrationNo
,ir.TruckTractorManufacturerName
,ir.ClientName
,ir.Capacity
,ir.Omc
,ir.EngineNo
,ir.TankLorryDimension
,ir.ChassisNo
,ir.InspectionPlace
,ir.TankLorryEnginePower
,ir.CarriageName
,ir.Brakes
,ir.IsSatisfactory
,ir.Remarks
,ir.Rev
,ir.Description
,ir.Status
,u1.UserName as PeparedBy
,u2.UserName as CheckedBy
,u3.UserName as ApprovedBy
,u4.UserName as IssuedBy
From InspectionReport ir
Inner Join dbo.[User] u1
ON u1.UserID= ir.PeparedBy
Inner Join dbo.[User] u2
ON u2.UserID= ir.CheckedBy
Inner Join dbo.[User] u3
ON u3.UserID= ir.ApprovedBy
Inner Join dbo.[User] u4
ON u4.UserID= ir.IssuedBy
where ir.InspectionReportID= #InspectionReportID
This is the stored procedure that is called by the function.
This the class inpsectionreport;
namespace VAILCertificates.DAL.Entities
{
public class InspectionReport
{
//General Details
public int InspectionReportID { get; set; }
[Required]
[Display (Name= "Velosi Project No")]
public string VelosiProjectNo { get; set; }
[Display(Name = "Velosi Report No")]
public string VelosiReportNo { get; set; }
[Required]
public string Reference { get; set; }
[Required]
[Display(Name = "PO No")]
public string PoNo { get; set; }
[Required]
[Display(Name = "Inspection Date")]
public DateTime InspectionDate { get; set; }
[Required]
[Display(Name = "Issue Date")]
public DateTime IssueDate { get; set; }
//Inspection Phase
[Required]
[Display(Name = "Inspection Phase")]
public byte InspectionPhase { get; set; } //0= Before, 1= During, 2= Final
//Types Of Inspection
[Display(Name = "In Service Inspection")]
public bool InServiceInspection { get; set; }
[Display(Name = "New Induction")]
public bool NewInduction { get; set; }
[Display(Name = "Hydorstatic Test")]
public bool HydrostaticTest { get; set; }
[Display(Name = "Dimensional Check")]
public bool DimensionalCheck { get; set; }
[Display(Name = "Thickness Check")]
public bool ThicknessCheck { get; set; }
[Display(Name = "PATROM")]
public bool Patrom { get; set; }
[Display(Name = "GVS")]
public bool Gvs { get; set; }
[Display(Name = "Final OGRA Inspection")]
public bool FinalOgraInspection { get; set; }
[Display(Name = "OMC/Client Requirement")]
public bool OmcClientRequirement { get; set; }
//Details Of Tank Lorry
[Required]
[Display(Name = "Tank Lorry Registration Number")]
public string TankLorryRegistrationNo { get; set; }
[Required]
[Display(Name = "Truck Tractor Manufacturer Name")]
public string TruckTractorManufacturerName { get; set; }
[Required]
[Display(Name = "Client Name")]
public string ClientName { get; set; }
[Required]
[Display(Name = "Capacity")]
public string Capacity { get; set; }
[Required]
[Display(Name = "OMC")]
public string Omc { get; set; }
[Required]
[Display(Name = "Engine No")]
public string EngineNo { get; set; }
[Required]
[Display(Name = "Tank Lorry Dimension")]
public string TankLorryDimension { get; set; }
[Required]
[Display(Name = "Chassis Number")]
public string ChassisNo { get; set; }
[Required]
[Display(Name = "Inspection Place")]
public string InspectionPlace { get; set; }
[Required]
[Display(Name = "Tank Lorry (Engine Power)")]
public string TankLorryEnginePower { get; set; }
[Required]
[Display(Name = "Carriage Name")]
public string CarriageName { get; set; }
[Required]
public string Brakes { get; set; }
//ResultsofInspection
[Required]
[Display(Name = "Is Satisfactory?")]
public bool IsSatisfactory { get; set; }
//Remarks
[Required]
public string Remarks { get; set; }
//ApprovalSection
public string Rev { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int PeparedBy { get; set; }
public int CheckedBy { get; set; }
public int ApprovedBy { get; set; }
public int IssuedBy { get; set; }
//ReportStatus
public byte Status { get; set; } //0= Prepared 1= CheckedBy 2= ApprovedBy
}
}
You can also construct a DbParameter and supply it as a parameter value to your stored procedure:
var InspectionReportID= new SqlParameter("#InspectionReportID", 0);
var list = this.Database.SqlQuery<InspectionReport>("EXECUTE dbo.GetInspectionReportDetails #InspectionReportID",InspectionReportID).ToList();
It is important to parameterize any user input to protect against a SQL injection attack. You can include parameter placeholders in the SQL query string and then supply parameter values as additional arguments. Any parameter values you supply will automatically be converted to a DbParameter.
Try changing the the sql statement, I feel the error is how you call the sql statement.
var list = this.Database.SqlQuery<InspectionReport>($"EXEC GetInspectionReportDetails {InspectionReportID}").ToList();
Try using this code:
public List<InspectionReport> GetInspectionReportDetails(int InspectionReportID)
{
var List= this.Database.SqlQuery<InspectionReport>("GetInspectionReportDetails #InspectionReportID", InspectionReportID).ToList();
return List;
}
i have 3 models
public class UsersModel
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 5", MinimumLength = 5)]
public string Name { get; set; }
//20150090
public int? student_ID { get; set; }
[Display(Name = "transcript")]
public string transcript { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 2", MinimumLength = 2)]
public string Department { get; set; }
[Required]
[Display(Name = "Phone")]
[DataType(DataType.PhoneNumber,ErrorMessage ="Invalid Phone Number")]
[Range(999999999, 9999999999)]
public int Phone { get; set; }
public int type { get; set; }
}
student
public class StudentsModel
{
[Key]
[Display(Name ="ID")]
public int StudentID { get; set; }
[Required]
public string Name { get; set; }
[Required]//20150090
public string student_ID { get; set; }
[Required]
[Display(Name = "Skills")]
public string Skills { get; set; }
[Required]
[Display(Name = "Gpa")]
[Range(1.00, 4.00, ErrorMessage = "It must be in range 0.00 to 4.00 :)")]
public float Gpa { get; set; }
[Required]
[Display(Name = "Leader")]
public string Leader { get; set; }
[Required]
[Display(Name = "transcript")]
public string transcript { get; set; }
[ForeignKey("UserId")]
public int UserId;
public UsersModel Users { get; set; }
[ForeignKey("IdeaId")]
public int? IdeaId;
public IdeaModel Idea { get; set; }
}
Idea
public class IdeaModel
{
[Required]
[Key]
public int IdeaId { get; set; }
[Required]
public string IdeaName { get; set; }
[Required]
public string IdeaDescription { get; set; }
[Required]
public string tools { get; set; }
public int? SetWith { get; set; }
[Required]
public int Prof1 { get; set; }
public int Prof2 { get; set; }
public int Prof3 { get; set; }
}
when i insert to the database user and student and idea
the foreign key in student model inserted with null value
this is the code for insertion
i want the foreign key in student model to inserted automatically
whit the values of primary key in usernodel and idea model how to make this?
public ActionResult RegisterLeader(regall reg)
{
if (ModelState.IsValid)
{
var user= db.Users.Add(reg.users);
var idea = db.Idea.Add(reg.idea);
var stu = db.Students.Add(reg.students[0]);
db.SaveChanges();
return View("RegisterLeaderPost");
//return Registerfinish();
}
}
this model have the three models
public class regall
{
public List<StudentsModel> students { get; set; }
public UsersModel users { get; set; }
public IdeaModel idea { get; set; }
}
You need to set the Idea property of the student so EF knows to make the relationship.
reg.students[0].Idea = reg.idea;
Right now my POST actions for Create and Edit have rather long function definitions because there are a lot of variables and my bind attribute contains all of them.
public ActionResult Create([Bind(Include = "ProjectName,ProjectDescription,DateReceived,EffectiveDate,ExpirationDate,GeneralContractor,ProjectTerm,ProjectType,SubmissionNumber,PolicyNumber,Status,Underwriter,Division,BrokerCity,TAName,Branch,FirstNamedInsuredAddress,FirstNamedInsured,ProjectAddress")] Project project) {
and
public ActionResult Edit([Bind(Include = "ProjectID,ProjectName,ProjectDescription,DateReceived,EffectiveDate,ExpirationDate,GeneralContractor,ProjectTerm,ProjectType,SubmissionNumber,PolicyNumber,Status,Underwriter,Division,BrokerCity,TAName,Branch,FirstNamedInsuredAddress,FirstNamedInsured,ProjectAddress")] Project project) {
Is there an alternative to this that would make the definitions shorter?
Here is my model:
public class Project
{
public Project()
{
FirstNamedInsuredAddress = new Address();
ProjectAddress = new Address();
}
[Key]
public int ProjectID { get; set; }
[Required]
[StringLength(150)]
[Display(Name = "Project Name")]
public string ProjectName { get; set; }
[StringLength(1000)]
[Display(Name = "Project Description")]
public string ProjectDescription { get; set; }
[Display(Name = "Date Received")]
public string DateReceived { get; set; }
[Display(Name = "Effective Date")]
public string EffectiveDate { get; set; }
[Display(Name = "Expiration Date")]
public string ExpirationDate { get; set; }
[StringLength(150)]
[Display(Name = "General Contractor")]
public string GeneralContractor { get; set; }
[StringLength(25)]
[Display(Name = "Project Term")]
public string ProjectTerm { get; set; }
[Display(Name = "Project Type")]
public string ProjectType { get; set; }
[Required]
[Display(Name = "Submission Number")]
public long SubmissionNumber { get; set; }
[StringLength(20)]
[Display(Name = "Policy Number")]
public string PolicyNumber { get; set; }
public string Status { get; set; }
[StringLength(100)]
public string Underwriter { get; set; }
public string Division { get; set; }
[StringLength(50)]
[Display(Name = "Broker/City")]
public string BrokerCity { get; set; }
[StringLength(100)]
[Display(Name="TA Name")]
public string TAName { get; set; }
public string Branch { get; set; }
[Display(Name="First Named Insured Address")]
public Address FirstNamedInsuredAddress { get; set; }
[StringLength(150)]
[Display(Name="First Named Insured")]
public string FirstNamedInsured { get; set; }
[Display(Name="Project Address")]
public Address ProjectAddress { get; set; }
public class Address
{
[StringLength(150)]
[Display(Name="Line 1")]
public string Line1 { get; set; }
[StringLength(150)]
[Display(Name="Line 2")]
public string Line2 { get; set; }
[StringLength(100)]
public string City { get; set; }
public string State { get; set; }
[Display(Name="Zip Code")]
public int? ZipCode { get; set; }
[StringLength(100)]
public string County { get; set; }
}
}
As an alternative to the Include , you can use the Exclude. It will only exclude the properties that you do not want post. Probably, it will lesser in most of the cases or if you want, you can remove both include and exclude , and all the data will be posted .
Ex:
[HttpPost]
[ActionName("Edit")]
public ActionResult Edit([Bind(Exclude = "GeneralContractor")] Project project)
{
}
More/Useful Information:http://csharp-video-tutorials.blogspot.in/2013/05/part-21-including-and-excluding.html
I want a different viewbag message displayed depending on which option is chosen from a dropdownlist of Enumerators however I'm not sure how to do this. Im using a viewmodel and passing the data through the controller, here is the ViewModel and class, an explanation on how to use if statements with ViewModels/Enumerators would be highly beneficial. I have tried assigning variables but Im realizing that all im doing is saying THIS is THIS, so thats not going to get the data from the Orders Postage enum. Any help and explanations appreciated, still learning.
ViewModel;
{
public class MyOrdersViewModel
{
public int OrderId { get; set; }
public System.DateTime OrderDate { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public decimal Total { get; set; }
public bool HasBeenShipped { get; set; }
public Postage? PostageList { get; set; }
public List<MyOrderDetails> Details { get; set; }
}
public class MyOrderDetails
{
public string Title { get; set; }
public string Colour { get; set; }
public int Quantity { get; set; }
public decimal UnitPrice { get; set; }
}
}
Controller;
public ActionResult Index(Order order)
{
string currentUser = this.User.Identity.GetUserName();
List<T_shirt_Company_v3.ViewModels.MyOrdersViewModel> list = (from o in new TshirtStoreDB().Orders
.Where(o => o.Username == currentUser)
.OrderByDescending(o => o.OrderDate)
.Select(o => new MyOrdersViewModel()
{
OrderId = o.OrderId,
Address = o.Address,
FirstName = o.FirstName,
LastName = o.LastName,
City = o.City,
OrderDate = o.OrderDate,
PostalCode = o.PostalCode,
Total = o.Total,
HasBeenShipped = o.HasBeenShipped,
PostageList = o.PostageList,
Details = (from d in o.OrderDetails
select new MyOrderDetails
{
Colour = d.Product.Colour,
Quantity = d.Quantity,
Title = d.Product.Title,
UnitPrice = d.UnitPrice
}).ToList()
}).ToList()
select o).ToList();
//#ViewBag.PostageStatus
//ViewBag.ShippedMessage = list.Where(w => w.HasBeenShipped).Any() ? "Order has been shipped" : "Order is being processed";
Postage value = Postage.FirstClass;
Postage value2 = Postage.StandardDelivery;
Postage value3 = Postage.TwentyFourHour;
if (value == Postage.FirstClass)
{
ViewBag.PostageStatus = ("First Class");
}
else
{
ViewBag.PostageStatus = (" Error ");
}
if (value2 == Postage.StandardDelivery)
{
ViewBag.PostageStatus = ("Standard Delivery");
}
if (value3 == Postage.StandardDelivery)
{
ViewBag.PostageStatus = ("24 hour delivery");
}
return View(list);
}
Order Class
namespace T_shirt_Company_v3.Models
{
//[Bind(Exclude = "OrderId")]
public partial class Order
{
[ScaffoldColumn(false)]
public int OrderId { get; set; }
[ScaffoldColumn(false)]
public System.DateTime OrderDate { get; set; }
[ScaffoldColumn(false)]
[Remote("CheckUserName", "Account")]
public string Username { get; set; }
[Required]
[StringLength(16, ErrorMessage = "Your name is too long")]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Your last name is required.")]
[StringLength(16, ErrorMessage = "Last name is too long.")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
[Required(ErrorMessage = "City is required.")]
public string City { get; set; }
[Required(ErrorMessage = "Postcode is required.")]
[Display(Name = "Post Code")]
public string PostalCode { get; set; }
[Required(ErrorMessage = "Country is required.")]
public string Country { get; set; }
[Required(ErrorMessage = "Phone number is required.")]
public string Phone { get; set; }
[RegularExpression(#"[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "Email doesn't look like a valid email address.")]
public string Email { get; set; }
[System.ComponentModel.DataAnnotations.Compare("Email")]
[Display(Name = "Confirm your email address")]
public string EmailConfirm { get; set; }
[ScaffoldColumn(false)]
public string PaymentTransactionId { get; set; }
[ScaffoldColumn(false)]
public bool HasBeenShipped { get; set; }
[ScaffoldColumn(false)]
//[ReadOnly(true)]
public decimal Total { get; set; }
[Required]
[Range(0, 2, ErrorMessage = "Select a delivery method")]
public Postage? PostageList { get; set; }
public CardDetails cardDetails { get; set; }
//public List<CardDetails> cardDetails { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
}
public enum Postage {[Display(Name = "Standard Delivery - Free")]StandardDelivery, [Display(Name = "First Class Delivery - £4.99")]FirstClass, [Display(Name = "24 Hour Delivery - £9.99")]TwentyFourHour }
}
Why not simply use a switch statement on the enum? Perhaps the misunderstanding was that the type was nullable. With nullables you can invoke .GetValueOrDefault and then switch on the return for the enum value.
switch (order.Postage.GetValueOrDefault())
{
case Postage.StandardDelivery:
ViewBag.PostageStatus = "Standard Delivery";
break;
case Postage.FirstClass:
ViewBag.PostageStatus = "First Class";
break;
case Postage.TwentyFourHour:
ViewBag.PostageStatus = "24 hour delivery";
break;
default:
ViewBag.PostageStatus = "Error";
break;
}
This prevents the usage of the if statement and simplifies the readability for the user.
I have annotations in two models, the two are related, ModelState.IsValid returns false when there are annotations, delete annotations if it works without problem, anyone know why this happens?
Model 1:
namespace SifActivoFijo.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class AF_UbicacionActivoFijo
{
public long IdUbicacion { get; set; }
[Required(ErrorMessage = "1*")]
[Display(Name = "Codigo Centro de Costo")]
public string GN_CentroDeCosto_CodigoCentroDeCosto { get; set; }
[Required(ErrorMessage = "2*")]
[Display(Name = "Tercero")]
public string GN_Persona_CodigoPersona { get; set; }
//[Required(ErrorMessage = "3*")]
[Display(Name = "Codigo Activo")]
public string AF_ActivoFijo_CodigoActivoFijo { get; set; }
[Required(ErrorMessage = "4*")]
[Display(Name = "Contacto")]
public string Contacto { get; set; }
[Required(ErrorMessage = "5*")]
[Display(Name = "Direccion")]
[RegularExpression(#"[A-Za-z_0-9\s .#&ñ'-]*\.?[A-Za-z_0-9\s .#&Ñ'-]+", ErrorMessage = "**")]
public string Direccion { get; set; }
[Required(ErrorMessage = "6*")]
[Display(Name = "Telefono")]
[RegularExpression(#"[A-Za-z_0-9\s .#&ñ'-]*\.?[A-Za-z_0-9\s .#&Ñ'-]+", ErrorMessage = "**")]
public string Telefono { get; set; }
[Required(ErrorMessage = "7*")]
[Display(Name = "Celular")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
public string Celular { get; set; }
[Required(ErrorMessage = "8*")]
[Display(Name = "Email")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Email { get; set; }
[Required(ErrorMessage = "9*")]
[Display(Name = "Responsable")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Responsable { get; set; }
[Required(ErrorMessage = "10*")]
[Display(Name = "Documento")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Responsable_documento { get; set; }
[Required(ErrorMessage = "11*")]
[Display(Name = "Telefono")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Responsable_Telefono { get; set; }
[Required(ErrorMessage = "12*")]
[Display(Name = "Sucursal")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string Sucursal { get; set; }
[Required(ErrorMessage = "13*")]
[Display(Name = "N° Contrato")]
[RegularExpression(#"[A-Za-z_0-9\s .##&ñ'-]*\.?[A-Za-z_0-9\s .##&Ñ'-]+", ErrorMessage = "**")]
public string NoContrato { get; set; }
[Required(ErrorMessage = "14*")]
[Display(Name = "Ciudad")]
public string GN_Nivel3_CodigoNivel3 { get; set; }
[Required(ErrorMessage = "15*")]
[Display(Name = "Fecha Inicial")]
public System.DateTime FechaInicial { get; set; }
public virtual GN_Nivel3 GN_Nivel3 { get; set; }
public virtual AF_ActivoFijo AF_ActivoFijo { get; set; }
public virtual GN_Persona GN_Persona { get; set; }
public virtual GN_CentroDeCosto GN_CentroDeCosto { get; set; }
}
}
Model 2:
namespace SifActivoFijo.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class AF_ActivoFijo
{
public AF_ActivoFijo()
{
this.AF_ConfiguracionActivoFijo = new HashSet<AF_ConfiguracionActivoFijo>();
this.AF_DepreciacionActivoFijo = new HashSet<AF_DepreciacionActivoFijo>();
this.AF_UbicacionActivoFijo = new HashSet<AF_UbicacionActivoFijo>();
this.AF_RevaluacionNIIF = new HashSet<AF_RevaluacionNIIF>();
}
[Required(ErrorMessage = "*1")]
[Display(Name = "Activo Fijo Principal")]
[RegularExpression(#"[A-Za-z_0-9 .#_-]*\.?[A-Za-z_0-9 .#_-]+", ErrorMessage = "**")]
public string CodigoActivoFijo { get; set; }
[Required(ErrorMessage = "*2")]
[Display(Name = "Grupo Contable")]
public string AF_GrupoContableAF_CodigoGrupoContableAF { get; set; }
[Required(ErrorMessage = "*3")]
[Display(Name = "Estado")]
public string ST_Estado_CodigoEstado { get; set; }
[Required(ErrorMessage = "*4")]
[Display(Name = "Grupo de Activo")]
public string AF_GrupoActivoFijo_CodigoGrupoAF { get; set; }
[Required(ErrorMessage = "*5")]
[Display(Name = "Producto")]
public string GN_Portafolio_CodigoPortafolio { get; set; }
[Display(Name = "Serial")]
[RegularExpression(#"[A-Za-z_0-9 .ñÑ#_-]*\.?[A-Za-z_0-9 .Ññ#_-]+", ErrorMessage = "**")]
public string Serial { get; set; }
[Display(Name = "Configurable")]
public bool SenConfigurable { get; set; }
[Required(ErrorMessage = "*6")]
[Display(Name = "Fecha de Activacion")]
public Nullable<System.DateTime> FechaActivacion { get; set; }
[Required(ErrorMessage = "*7")]
[Display(Name = "Costo")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
[DataType(DataType.Currency)]
public Nullable<double> Costo { get; set; }
[Required(ErrorMessage = "*8")]
[Display(Name = "IVA")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
public Nullable<double> ValorIva { get; set; }
[Required(ErrorMessage = "*9")]
[Display(Name = "Margen")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
public Nullable<double> PorcentajeMargen { get; set; }
[Display(Name = "Costo Activo")]
[RegularExpression(#"[0-9 ]*\.?[0-9 ]+", ErrorMessage = "**")]
public Nullable<double> CostoActivo { get; set; }
[Display(Name = "Tiempo Contable")]
public Nullable<int> TiempoDepreciacionContable { get; set; }
[Display(Name = "Tiempo Fiscal")]
public Nullable<int> TiempoDepreciacionFiscal { get; set; }
[Display(Name = "Depreciable Individiual")]
public bool SenDepreciacionIndividual { get; set; }
[Display(Name = "Saldo Contable")]
public Nullable<double> SaldoADepreciar { get; set; }
[Required(ErrorMessage = "*10")]
[RegularExpression(#"[A-Za-z_0-9\s .#&ñ'-]*\.?[A-Za-z_0-9\s .#&Ñ'-]+", ErrorMessage = "**")]
public string DescripcionActivoFijo { get; set; }
[Display(Name = "Saldo Fiscal")]
public Nullable<double> SaldoAdepreciarFiscal { get; set; }
[Display(Name = "Depreciable")]
public bool SenDepreciable { get; set; }
[Required(ErrorMessage = "*11")]
[Display(Name = "Propietario")]
public string GN_Persona_CodigoPersona { get; set; }
public Nullable<double> SaldoNiif { get; set; }
public Nullable<int> VidaUtilNiif { get; set; }
public Nullable<System.DateTime> FechaReevaluacion { get; set; }
public virtual AF_GrupoActivoFijo AF_GrupoActivoFijo { get; set; }
public virtual AF_GrupoContableAF AF_GrupoContableAF { get; set; }
public virtual GN_Portafolio GN_Portafolio { get; set; }
public virtual ST_Estado ST_Estado { get; set; }
public virtual ICollection<AF_ConfiguracionActivoFijo> AF_ConfiguracionActivoFijo { get; set; }
public virtual ICollection<AF_DepreciacionActivoFijo> AF_DepreciacionActivoFijo { get; set; }
public virtual ICollection<AF_UbicacionActivoFijo> AF_UbicacionActivoFijo { get; set; }
public virtual ICollection<AF_RevaluacionNIIF> AF_RevaluacionNIIF { get; set; }
}
}
CONTROLLER
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(AF_UbicacionActivoFijo ubicacion)
{
AF_UbicacionActivoFijo au = new AF_UbicacionActivoFijo {
IdUbicacion=ubicacion.IdUbicacion,
GN_CentroDeCosto_CodigoCentroDeCosto=ubicacion.GN_CentroDeCosto_CodigoCentroDeCosto,
GN_Persona_CodigoPersona=ubicacion.GN_Persona_CodigoPersona,
AF_ActivoFijo_CodigoActivoFijo=ubicacion.AF_ActivoFijo_CodigoActivoFijo,
Contacto=ubicacion.Contacto,
Direccion=ubicacion.Direccion,
Telefono=ubicacion.Telefono,
Celular=ubicacion.Celular,
Email=ubicacion.Email,
Responsable=ubicacion.Responsable,
Responsable_documento=ubicacion.Responsable_documento,
Responsable_Telefono=ubicacion.Responsable_Telefono,
Sucursal=ubicacion.Sucursal,
NoContrato=ubicacion.NoContrato,
GN_Nivel3_CodigoNivel3=ubicacion.GN_Nivel3_CodigoNivel3,
FechaInicial=ubicacion.FechaInicial
};
if (ModelState.IsValid)
{
db.Entry(au).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("confirm", "Home");
}
else
{
foreach (var modelStateValue in ViewData.ModelState.Values)
{
foreach (var error in modelStateValue.Errors)
{
//Use breakpoints and Let's check what it is in these properties
var errorMessage = error.ErrorMessage;
var exception = error.Exception;
}
}
}
ViewBag.GN_Nivel3_CodigoNivel3 = new SelectList(db.GN_Nivel3, "CodigoNivel3", "NombreNivel3", ubicacion.GN_Nivel3_CodigoNivel3);
ViewBag.GN_CentroDeCosto_CodigoCentroDeCosto = new SelectList(db.GN_CentroDeCosto, "CodigoCentroDeCosto", "NombreCentroDeCosto", ubicacion.GN_CentroDeCosto_CodigoCentroDeCosto);
return View(ubicacion);
}
Data annotations work as validations on models and when we do model.IsValid then all annotations are validated against the values we assign to model properties , it seems that any of your regular expression is not validating your assigned value.