Data Annotations In mvc - asp.net-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
}
}

Related

Can't get a List of objects from a model in Razor CSHTML page

This is my first time posting to Stack Overflow. So forgive me if I am not asking the question properly.
I have created a Razor page (in 4.72) wherein the Employer model has a List of Employee models embedded into the Employer model as well. I have Razor page with the Employer information on top and entries for multiple employees below. When submitting the page to create the employer, and employees, I am passing the Employer model into Action Result . But for some reason the List of Employees doesn't come with the Employer model.
The Employer Model and it's values comes over just fine., but not Employees.
My Razor page:
#model FraudReports.Models.FraudReportEmployer
#{
ViewBag.Title = "CreateEmployee";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
#Html.LabelFor(model => model.EmployerName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmployerName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmployerName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FEIN, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FEIN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FEIN, "", new { #class = "text-danger" })
</div>
</div>
<!-- More form Employer fields here -->
<!-- Start list of Employees here (Number of Employees could vary, using 5 entries for now. )-->
#{
for (var i = 1; i < 5; i++)
{
<hr />
<div class="form-group">
#Html.LabelFor(model => model.FraudReportEmployees[i].FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FraudReportEmployees[i].FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FraudReportEmployees[i].FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FraudReportEmployees[i].MI, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FraudReportEmployees[i].MI, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FraudReportEmployees[i].MI, "", new { #class = "text-danger" })
</div>
</div>
<!-- More form Employee fields here -->
}
<!-- End list of Employee fields here -->
}
<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>
My Action method:
public ActionResult CreateEmployee(FraudReportEmployer fraudReportEmployer)
{
List<FraudReportEmployee> FraudReportEmployees = fraudReportEmployer.FraudReportEmployees;
! There are values in Employer model but not the Employee List inside.
.
.
return View();
}
The Employer Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FraudReports.Models
{
public class FraudReportEmployer
{
public string EmployerName { get; set; }
public string ContactName { get; set; }
public string ContactPhone { get; set; }
public string ContactEmail { get; set; }
....
public List<FraudReportEmployee> FraudReportEmployees { get; set; }
}
}
Employee MOdel:
namespace FraudReports.Models
{
public class FraudReportEmployee
{
public string EmployeeId { get; set; }
public string FirstName { get; set; }
public string MI { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
}
}
The indexing should be started from 0, like
for (var i = 0; i < 5; i++)
When the first element in the collection is missing the MVC can't bind the collection elements properly.

how can I pass the context from both the class in the MODEL to one view without this error?

In a MODEL, I have two class - ContentDetails and CompetencyDetails which contains its properties
namespace CompetencyAssessmentServices.ServiceModel
{
public class ContentDetails
{
public int CaseStudyId { get; set; }
public string CaseStudy { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public bool IsActive { get; set; }
public bool ReviewStatus { get; set; }
public string SolutionDescription { get; set; }
public int CompetencyID { get; set; }
public string CompetencyName { get; set; }
public List<string> SolutionId { get; set; }
}
public class CompetencyDetails
{
public int CompID { get; set; }
public string CompName { get; set; }
}
}
Controller :
Action CaseStudy is retrieving the list of CompetencyDetails from database which is working fine.
namespace CompetencyAssessment.Controllers
{
public class ContentManagementController : Controller
{
// GET: ContentManagement
IContentManagementRepository repo = new ContentManagementRepository();
[HttpGet]
public ActionResult CaseStudy()
{
List<CompetencyDetails> complst = repo.GetCompetencyDetails();
ViewBag.list = complst;
return View(ViewBag.list);
}
[HttpPost]
public ActionResult CaseStudy(ContentDetails cd)
{
ContentDetails ctd = repo.CaseStudyCreationDetails(cd);
return View();
}
}
}
While loading the View, I am getting below error
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[CompetencyAssessmentServices.ServiceModel.CompetencyDetails]', but this dictionary requires a model item of type 'CompetencyAssessmentServices.ServiceModel.ContentDetails'.
View is
#model CompetencyAssessmentServices.ServiceModel.ContentDetails
#{
ViewBag.Title = "CASE-STUDY Contenet Creation (By SME)";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CASE-STUDY Contenet Creation (By SME)</title>
</head>
<body>
#using (Html.BeginForm())
{
<h4>ContentDetails</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.CaseStudy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.CaseStudy, new { htmlAttributes = new { #class = "form-control", style = "rows=20,columns=400" } })
#Html.ValidationMessageFor(model => model.CaseStudy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsActive, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsActive)
#Html.ValidationMessageFor(model => model.IsActive, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
Solution 1: #Html.TextBox("Sol1") #Html.DropDownList("CompetencyDetails", new SelectList(ViewBag.list, "CompID", "CompName"), "Select Competency")
Solution 2: #Html.TextBox("Sol2") #Html.DropDownList("CompetencyDetails", new SelectList(ViewBag.list, "CompID", "CompName"), "Select Competency")
Solution 3: #Html.TextBox("Sol3") #Html.DropDownList("CompetencyDetails", new SelectList(ViewBag.list, "CompID", "CompName"), "Select Competency")
Solution 4: #Html.TextBox("Sol4") #Html.DropDownList("CompetencyDetails", new SelectList(ViewBag.list, "CompID", "CompName"), "Select Competency")
<div class="form-group">
#Html.LabelFor(model => model.SolutionId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SolutionId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SolutionId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SolutionDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SolutionDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SolutionDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
</body>
</html>
The reason, I am getting this error because my view contains the reference from both class CompetencyDetails and ContentDetails
Can someone please help on how can I pass the context from both the class in the MODEL without this error ?
PS: This is my first MVC project so would appreciate any various approaches to achieve this
you can create new class having both the model class like example given below
public class Combine
{
public List<ContentDetails> ContentDetailsList { get; set; }
public ContentDetails ContentDetailsData { get; set; }
public List<CompetencyDetails> CompetencyDetailsInfoList { get; set; }
public CompetencyDetails CompetencyDetailsData { get; set; }
}
then in MVC controller
[HttpGet]
public ActionResult CaseStudy()
{
var caseStudy = new SupplierDTO()
{
ContentDetailsList = db.ContentDetails.ToList(),
CompetencyDetailsInfoList = db.CompetencyDetails.ToList(),
};
return View(caseStudy);
}
then MVC View
#model CompetencyAssessmentServices.Models.Combine
<div class="form-group">
#Html.LabelFor(model => model.ContentDetailsData.CaseStudy, htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.EditorFor(model => model.ContentDetailsData.CaseStudy, new { htmlAttributes = new { #class = "form-control"} })
#Html.ValidationMessageFor(model => model.ContentDetailsData .CaseStudy, "", new { #class = "text-danger"})
</div>
</div>

MVC 5 dropdown value when selected

I have a category and sub category dropdown list in my view. I select the items in the DDL and submit. In my controller I can only see the categoryID, subCategoryID values for the DDL. I need to get the selected text values (categoryName, subCategoryName). In winforms it is known as the DisplayMember.
I can get the categoryName, subcategoryName values if I run a query based on the returned ID, but this feels like I'm hitting the database more times than I need to.
Here is my code:
ViewModel
public class MedicalCategoryVM
{
public int PersonID { get; set; }
public int CategoryID { get; set; }
public string CategoryName { get; set; }
public int SubCategoryID { get; set; }
public string SubCategoryName { get; set; }
public string Notes { get; set; }
public Nullable<System.Guid> RowGuid { get; set; }
public Nullable<System.DateTime> ModifiedDate { get; set; }
public virtual Person Person { get; set; }
public List<MedicalCategory> MedicalCategories { get; set; }
}
View:
#model DofE.Models.MedicalCategoryVM
<br />
<br />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="container">
#Html.Label("Medical Information", new { style = "font-size:16px; background-color:#002142; color:white;margin-left:10px" })
<div class="form-group">
#Html.DropDownListFor(model => model.CategoryID, new SelectList(Model.MedicalCategories,"CategoryID","CategoryName"),"--Select", new { #class = "form-control" })
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.SubCategoryID, new SelectList(""), "--Select Sub Category", new { #class = "form-control" })
</div>
<div class="form-group">
<div class="row">
#Html.LabelFor(model => model.Notes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Notes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Notes, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="row">
#Html.LabelFor(model => model.PersonID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PersonID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PersonID, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div style="padding-left:340px">
<span style="display: inline;">
#Html.ActionLink("Cancel", "Index", null, new { #class = "btn btn-danger btn-sm" }) <input type="submit" value="Create" class="btn btn-primary btn-sm" />
</span>
</div>
#*<div class="test">
<div style="float: right;">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>*#
</div>
</div>
}
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CategoryID").change(function () {
$.get("/MedicalHistory/GetSubCategoryList", { CategoryID: $("#CategoryID").val() }, function (data) {
$("#SubCategoryID").empty();
$.each(data, function (index, row) {
$("#SubCategoryID").append("<option value='" + row.SubCategoryID + "'>" + row.SubCategoryName + "</option>")
});
});
})
});
</script>
Controller:
public ActionResult Create()
{
MedicalCategoryVM CategoryVM = new MedicalCategoryVM();
CategoryVM.MedicalCategories = db.MedicalCategories.ToList();
//ViewBag.CategoryList = new SelectList(CategoryList, "CategoryID", "CategoryName");
return View(CategoryVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "PersonID,CategoryName,SubCategoryName,Notes,RowGuid,ModifiedDate")] MedicalHistory medicalHistory, FormCollection form)
{
//string catName = form["CategoryName"].ToString();
//string subCatName = form["SubCategoryName"].ToString();
int catID = Convert.ToInt16(form["CategoryID"]);
int subCatID = Convert.ToInt16(form["SubCategoryID"]);
MedicalSubCategory cat = db.MedicalSubCategories.Find(subCatID);
medicalHistory.CategoryName = cat.CategoryName;
medicalHistory.SubCategoryName=cat.SubCategoryName;
medicalHistory.RowGuid = Guid.NewGuid();
medicalHistory.ModifiedDate = DateTime.Now;
if (ModelState.IsValid)
{
db.MedicalHistories.Add(medicalHistory);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(medicalHistory);
}

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.

modelstate.isvalid not getting all the errors

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

Resources