Adding CheckBoxList of items to MVC 4 View - asp.net

I have the challenge of adding CheckBoxList of items to MVC 4 view. I have several models in the same the MVC 4 view. So I created the View Model below
public class ArticlesVM
{
public article articles { get; set; }
public game games { get; set; }
public gallery mgallery { get; set; }
public team teams { get; set; }
public ArticlesVM()
{
Teams = new List<TeamVM>();
}
public List<TeamVM> Teams { get; set; }
}
to include 4 models as it properties. I then created a view where each of the properties can be used independently as follows:
#model TeamBuildingCompetition.ViewModels.ArticlesVM
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout_new.cshtml";
}
<h2>Index</h2>
#using (Html.BeginForm("Create", "TBCArticles", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4></h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.articles.featuredImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.TextBoxFor(model => model.articles.featuredImage, new { #type = "file" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.games.gameName, "Select a Game", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownList("gameID", (IEnumerable<SelectListItem>)ViewBag.gameList, "Select Game", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.HiddenFor(model => model.teams.teamID)
#Html.HiddenFor(model => model.teams.teamName)
#Html.DisplayFor(model => model.teams.teamName)
<div class="col-md-8">
#for(int i = 0; i < Model.Teams.Count; i++){
#Html.HiddenFor(model => model.Teams[i].ID)
#Html.CheckBoxFor(model => model.Teams[i].IsSelected)
#Html.LabelFor(model => model.Teams[i].IsSelected, Model.Teams[i].TeamName)
}
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.articles.articleTitle, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.articles.articleTitle, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.articles.articleTitle, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.articles.articleContent, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.articles.articleContent, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.articles.articleContent, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.mgallery.picturePath, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.TextBoxFor(model => model.mgallery.picturePath, new { #type = "file", #multiple = "true" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-8">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Here is my TeamVM model below:
public class TeamVM
{
public int ID { get; set; }
[Required(ErrorMessage = "Please Enter Your Team Name")]
[Display(Name = "Team Name")]
public string TeamName { get; set; }
[DisplayName("Team Picture")]
[ValidateFile]
public HttpPostedFileBase TeamPicture { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required(ErrorMessage = "Please Enter Team Content")]
[Display(Name = "Content")]
[MaxLength(500)]
public string Content { get; set; }
public bool IsSelected { get; set; }
}
Added the following to my controller action:
[HttpGet]
public ActionResult Index(ArticlesVM model)
{
model = new ArticlesVM ();
model = new ArticlesVM();
var teamList = (from p in db.teams
select new TeamVM()
{
ID = p.teamID,
TeamName = p.teamName,
IsSelected = p.IsSelected
});
model.Teams = teamList.ToList();
ViewBag.gameList = new SelectList(db.games, "gameID", "gameName");
return View(model);
}
And now have a null reference error in this portion of the view:
<div class="form-group">
#Html.HiddenFor(model => model.teams.teamID)
#Html.DisplayFor(model => model.teams.teamName)
<div class="col-md-8">
#for(int i = 0; i < Model.Teams.Count; i++){
#Html.HiddenFor(model => model.Teams[i].ID)
#Html.CheckBoxFor(model => model.Teams[i].IsSelected)
#Html.LabelFor(model => model.Teams[i].IsSelected, Model.Teams[i].TeamName)
}
</div>
</div>

Related

Using Ajax to Update database in ASP.net MVC

I'm trying to implement AJAX to update the existing record in my database, but it is neither showing "success" message nor "error" message.
I have saved id of variable in "value" by "value = Model.ID". I passed the correct row from my controller.
Script code:
$("#button").click(function () {
var upid = $('#hide').val();
var values = {
Email: $('#txtEmail').val(),
FirstName: $('#fname').val(),
LastName: $('#lname').val(),
MobileNumber: $('#num').val(),
DateOfBirth: $('#dob').val(),
Password: $('#pwd').val(),
}
$.ajax({
url: '/Populations/UpdatePopulation',
method: 'POST',
data: {
std: values,
id: upid
},
success: function () {
alert("Updated");
},
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
}
});
});
Controller(for making updates):
[HttpPost]
public ActionResult UpdatePopulation(Population std, int id)
{
{
Population updatestd = db.Populations.Find(id);
if (!string.IsNullOrWhiteSpace(std.Email)) { updatestd.Email = std.Email; }
if (!string.IsNullOrWhiteSpace(std.FirstName)) { updatestd.FirstName = std.FirstName; }
if (!string.IsNullOrWhiteSpace(std.LastName)) { updatestd.LastName = std.LastName; }
{ updatestd.MobileNumber = std.MobileNumber; }
{ updatestd.DateOfBirth = std.DateOfBirth; }
{ updatestd.Password = std.Password; }
db.SaveChanges();
}
return Json(true, JsonRequestBehavior.AllowGet);
}
Html code without _layout.cshtml file:
#model OfficeWork.Models.Population
#{
ViewBag.Title = "Edit";
}
#{
var value = Model.ID;
}
#section navbar{
<div class="container-fluid">
<div class="navbar-header">
<P class="navbar-brand">PROJECT</P>
</div>
<ul class="nav navbar-nav">
<li class="active" style="cursor:pointer;"><a>User Details</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>#Html.ActionLink(" Log Out", "SignIn", "populations", htmlAttributes: new { #class = "glyphicon glyphicon-user" })</li>
</ul>
</div>
}
<div class="container" style="margin-top:10%">
<form method="post">
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control", #type = "email", #placeholder = "Enter email", #id = "txtEmail" } })
#Html.ValidationMessageFor(model => model.Email, "", 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", #type = "text", #id = "fname", #placeholder = "Frist Name" }
})
#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", #type = "text", #id = "lname", #placeholder = "Last Name" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MobileNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MobileNumber, new { htmlAttributes = new { #class = "form-control", #id = "num", #placeholder = "Mobile Number" } })
#Html.ValidationMessageFor(model => model.MobileNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { #class = "form-control", #type = "date", #id = "dob" } })
#Html.ValidationMessageFor(model => model.DateOfBirth, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control", #type = "password", #id = "pwd", #placeholder = "Enter password", #onkeyup = "Check()" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="renterpwd">Repeat Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="renterpwd" placeholder="Repeat password" onkeyup="Check()">
<span id="error"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save Details" class="btn btn-default" id="button" />
</div>
</div>
</div>
</form>
<br />
<div id="divErrorText"></div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/js")
}
<input id="hide" type="hidden" value="#value" />
Modal class:
using System;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace OfficeWork.Models
{
public class Population
{
[Key]
public int ID { get; set; }
[Required]
[Display(Name ="Email")]
[EmailAddress(ErrorMessage ="Enter valid email address")]
public string Email { get; set; }
[StringLength(10)]
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[StringLength(10)]
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Display(Name = "Mobile Number")]
[Required]
public long MobileNumber { get; set; }
[Display(Name = "Date Of Birth")]
[Required]
public DateTime DateOfBirth { get; set; }
[Display(Name = "Password")]
[Required]
public string Password { get; set; }
}
public class PopulationDBContext : DbContext
{
public DbSet<Population> Populations { get; set; }
}
}
I tried to execute "alert" message in my script to check whether my script uploaded successfully and it worked fine. This means I successfully uploaded my script though "bundle.config" file. "bundles.Add(new ScriptBundle("~/bundles/js").Include("~/Scripts/Edit.js"));"
fix you submit button by removing submit type
<input value="Save Details" class="btn btn-default" id="submitButton" />
and try to wrap your script
$(document).ready(function () {
$(document).on("click", "#submitButton",
function (e) {
e.preventDefault();
e.stopImmediatePropagation();
.... your code
success: function (result) {
alert("Updated");
},
.... your code
});
});
and check up developer tools in your browser for javascript errors

How can i use a list of properties with razor to complete the crud

I'm working on a project with .NET framework and asp.net, it's a web application that can handle certain forms for an insurance company.
The concept is to fill the forms in order to complete the registration.
For that i have created 5 classes, each class has certain properties as following :
class 1 :
public class BulletinAdhesionRMA
{
[Key]
public int BulletinId { get; set; }
[Required]
[Display(Name = "Type de bulletin")]
public TypeBulletinEnum TypeBulletin { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "N° d'adhésion")]
public string NumeroAdhesion { get; set; }
[Required]
public Employeur Employeur { get; set; }
[Required]
[StringLength(15)]
public string Nom { get; set; }
[Required]
[StringLength(15)]
[Display(Name = "Prénom")]
public string Prenom { get; set; }
[StringLength(15)]
[Display(Name = "Nom de jeune fille (Si affilié de sexe féminin)")]
public string NomJeuneFille { get; set; }
[Required]
public Sexe Genre { get; set; }
[Required]
[Display(Name = "Situation de famille")]
public SituationFamille SituationFamiliale { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Date de naissance")]
public DateTime DateNaissance { get; set; }
[Required]
[Display(Name = "Type de document d'identification (Cin, passeport, etc...)")]
public TypeDocumentIdentification TypeDocument { get; set; }
[Required]
[StringLength(15)]
[Display(Name = "N° document")]
public string NumeroDocument { get; set; }
[Required]
[StringLength(60)]
public string Adresse { get; set; }
[Required]
[StringLength(20)]
public string Ville { get; set; }
[Required]
[StringLength(10)]
public string Pays { get; set; }
[StringLength(15)]
[Phone]
[Display(Name = "Téléphone")]
public string Telephone { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Date d'affiliation")]
public DateTime DateAffiliation { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Date d'entrée en fonction")]
public DateTime DateEntreeFonction { get; set; }
[Display(Name = "Catégorie du personnel")]
[StringLength(50)]
public string CategoriePersonnel { get; set; }
[StringLength(50)]
public string Emploi { get; set; }
[StringLength(50)]
public string Matricule { get; set; }
[Display(Name = "Salaire annuel (ou capital)")]
public double SalaireAnnuel { get; set; }
public List<BeneficiaireConjoint> BeneficiareConjoints { get; set; }
public List<BeneficiaireEnfant> BeneficiareEnfants { get; set; }
public List<BeneficiaireEnCasDeces> BeneficiareEnCasDeces { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Le :")]
public DateTime FaitLe { get; set; }
[Required]
[StringLength(60)]
[Display(Name = "Fait à")]
public string FaitA { get; set; }
}
class 2 :
public class Employeur
{
[Key,ForeignKey("BulletinAdhesionRMA")]
public int EmployeurId { get; set; }
public BulletinAdhesionRMA BulletinAdhesionRMA { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "N° Client")]
public string NumeroClient { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "N° Filiale")]
public string NumeroFiliale { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Raison Social")]
public string RaisonSocial { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "N° Contrat")]
public string NumeroContrat { get; set; }
[Required]
[StringLength(50)]
public string Adresse { get; set; }
}
class 3 :
public class BeneficiaireConjoint
{
[Key]
public string Code { get; set; }
public int? BulletinId { get; set; }
[ForeignKey("BulletinId")]
public BulletinAdhesionRMA BulletinAdhesionRMA { get; set; }
[StringLength(15)]
public string Nom { get; set; }
[StringLength(15)]
[Display(Name = "Prénom")]
public string Prenom { get; set; }
public Sexe? Genre { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date de naissance")]
public DateTime? DateNaissance { get; set; }
}
class 4 :
public class BeneficiaireEnfant
{
[Key]
public string Code { get; set; }
public int? BulletinId { get; set; }
[ForeignKey("BulletinId")]
public BulletinAdhesionRMA BulletinAdhesionRMA { get; set; }
[StringLength(15)]
public string Nom { get; set; }
[StringLength(15)]
[Display(Name = "Prénom")]
public string Prenom { get; set; }
public Sexe? Genre { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date de naissance")]
public DateTime? DateNaissance { get; set; }
}
class 5 :
public class BeneficiaireEnCasDeces
{
[Key]
public string Code { get; set; }
public int? BulletinId { get; set; }
[ForeignKey("BulletinId")]
public BulletinAdhesionRMA BulletinAdhesionRMA { get; set; }
[StringLength(15)]
public string Nom { get; set; }
[StringLength(15)]
[Display(Name = "Prénom")]
public string Prenom { get; set; }
public Sexe? Genre { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Date de naissance")]
public DateTime? DateNaissance { get; set; }
}
After that, i have created the "DbContext" in order to create the database structure :
public class BulletinAdhesionDbContext : DbContext
{
public BulletinAdhesionDbContext() : base("BulletinAdhesionConnectionString")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<BulletinAdhesionDbContext, Configuration>());
}
public DbSet<BulletinAdhesionRMA> BulletinAdhesionsRMA { get; set; }
public DbSet<Employeur> Employeurs { get; set; }
public DbSet<BeneficiaireConjoint> BeneficiaireConjoints { get; set; }
public DbSet<BeneficiaireEnfant> BeneficiaireEnfants { get; set; }
public DbSet<BeneficiaireEnCasDeces> BeneficiaireEnCasDeces { get; set; }
}
Also, i'm gonna need a "controller" to make things as they're supposed to be :
public class BulletinAdhesionRMAController : Controller
{
public BulletinAdhesionDbContext db = new BulletinAdhesionDbContext();
// GET: BulletinAdhesionRMA
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "" )] BulletinAdhesionRMA bulletinAdhesionRMA)
{
if(ModelState.IsValid)
{
db.BulletinAdhesionsRMA.Add(bulletinAdhesionRMA);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View();
}
}
And finally the view responsible for the form filling :
#model BulletinAdhesion.Models.BulletinAdhesionRMA
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("Index", "BulletinAdhesionRMA", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="row" id="rma" >
<div class="col-12">
<div class="row">
<div class="col-sm-4">
<img class="img-responsive" src="~/logos/rma.png" width="50" />
</div>
</div>
<div class="row">
<div class="col-sm-4">
<div class="m-b-10">
#Html.LabelFor(model => model.TypeBulletin)
#Html.EnumDropDownListFor(model => model.TypeBulletin, new { #class = "form-control" })
</div>
#Html.ValidationMessageFor(model => model.TypeBulletin, "", new { #class = "text-danger" })
</div>
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(Model => Model.NumeroAdhesion)
#Html.EditorFor(Model => Model.NumeroAdhesion, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.NumeroAdhesion, "", new { #class = "text-danger" })
</div>
</div>
<div class="card-header custom-card-header">
<h4>Employeur : </h4>
</div>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(Model => Model.Employeur.NumeroClient)
#Html.EditorFor(Model => Model.Employeur.NumeroClient, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Employeur.NumeroClient, "", new { #class = "text-danger" })
</div>
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(Model => Model.Employeur.NumeroContrat)
#Html.EditorFor(Model => Model.Employeur.NumeroContrat, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Employeur.NumeroContrat, "", new { #class = "text-danger" })
</div>
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(Model => Model.Employeur.NumeroFiliale)
#Html.EditorFor(Model => Model.Employeur.NumeroFiliale, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Employeur.NumeroFiliale, "", new { #class = "text-danger" })
</div>
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(Model => Model.Employeur.RaisonSocial)
#Html.EditorFor(Model => Model.Employeur.RaisonSocial, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Employeur.RaisonSocial, "", new { #class = "text-danger" })
</div>
<div class="col-sm-4">
<div class="form-group">
#Html.LabelFor(Model => Model.Employeur.Adresse)
#Html.EditorFor(Model => Model.Employeur.Adresse, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Employeur.Adresse, "", new { #class = "text-danger" })
</div>
</div>
<div class="card-header custom-card-header">
<h4>Adhérent : </h4>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Nom)
#Html.EditorFor(model => model.Nom, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Nom, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Prenom)
#Html.EditorFor(model => model.Prenom, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Prenom, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.NomJeuneFille)
#Html.EditorFor(model => model.NomJeuneFille, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.NomJeuneFille, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Genre)
#Html.EnumDropDownListFor(model => model.Genre, new { #class = "form-control" })
</div>
#Html.ValidationMessageFor(model => model.Genre, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.DateNaissance)
#Html.EditorFor(model => model.DateNaissance, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.DateNaissance, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.SituationFamiliale)
#Html.EnumDropDownListFor(model => model.SituationFamiliale, new { #class = "form-control" })
</div>
#Html.ValidationMessageFor(model => model.SituationFamiliale, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.TypeDocument)
#Html.EnumDropDownListFor(model => model.TypeDocument, new { #class = "form-control" })
</div>
#Html.ValidationMessageFor(model => model.TypeDocument, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.NumeroDocument)
#Html.EditorFor(model => model.NumeroDocument, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.NumeroDocument, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Adresse)
#Html.EditorFor(model => model.Adresse, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Adresse, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Ville)
#Html.EditorFor(model => model.Ville, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Ville, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Pays)
#Html.EditorFor(model => model.Pays, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Pays, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Telephone)
#Html.EditorFor(model => model.Telephone, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Telephone, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.DateAffiliation)
#Html.EditorFor(model => model.DateAffiliation, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.DateAffiliation, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.DateEntreeFonction)
#Html.EditorFor(model => model.DateEntreeFonction, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.DateEntreeFonction, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.CategoriePersonnel)
#Html.EditorFor(model => model.CategoriePersonnel, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.CategoriePersonnel, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Emploi)
#Html.EditorFor(model => model.Emploi, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Emploi, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.Matricule)
#Html.EditorFor(model => model.Matricule, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.Matricule, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.SalaireAnnuel)
#Html.EditorFor(model => model.SalaireAnnuel, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.SalaireAnnuel, "", new { #class = "text-danger" })
</div>
</div>
<div class="card-header custom-card-header">
<h4>Bénéficiaire (s) Prestations maladie : </h4>
</div>
<div class="row" style="margin-bottom:25px !important;">
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>Code</th>
<th>Nom (jeune fille)</th>
<th>Prénom</th>
<th>Sexe</th>
<th>Date de naissance</th>
</tr>
</thead>
#*<tbody>
<tr>
<td>CO1</td>
<td>#Html.EditorFor(model => model.BeneficiareConjoints[0].Nom, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareConjoints[0].Nom, "", new { #class = "text-danger" })</td>
<td>#Html.EditorFor(model => model.BeneficiareConjoints[0].Prenom, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareConjoints[0].Prenom, "", new { #class = "text-danger" })</td>
<td>#Html.EnumDropDownListFor(model => model.BeneficiareConjoints[0].Genre, new { #class = "form-control" })#Html.ValidationMessageFor(model => model.BeneficiareConjoints[0].Genre, "", new { #class = "text-danger" })</td>
<td>#Html.EditorFor(model => model.BeneficiareConjoints[0].DateNaissance, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareConjoints[0].DateNaissance, "", new { #class = "text-danger" })</td>
</tr>
<tr>
<td>CO2</td>
<td>#Html.EditorFor(model => model.BeneficiareConjoints[1].Nom, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareConjoints[1].Nom, "", new { #class = "text-danger" })</td>
<td>#Html.EditorFor(model => model.BeneficiareConjoints[1].Prenom, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareConjoints[1].Prenom, "", new { #class = "text-danger" })</td>
<td>#Html.EditorFor(model => model.BeneficiareConjoints[1].Genre, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareConjoints[1].Genre, "", new { #class = "text-danger" })</td>
<td>#Html.EditorFor(model => model.BeneficiareConjoints[1].DateNaissance, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareConjoints[1].DateNaissance, "", new { #class = "text-danger" })</td>
</tr>
</tbody>
<thead>
<tr>
<th>Code</th>
<th>Prénom</th>
<th>Sexe</th>
<th>Date de naissance</th>
</tr>
</thead>
<tbody>
#for (int i = 1; i <= 11; i++)
{
<tr>
<td>EO #i</td>
<td>#Html.EditorFor(model => model.BeneficiareEnfants[i - 1].Prenom, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareEnfants[i - 1].Prenom, "", new { #class = "text-danger" })</td>
<td>#Html.EditorFor(model => model.BeneficiareEnfants[i - 1].Genre, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareEnfants[i - 1].Genre, "", new { #class = "text-danger" })</td>
<td>#Html.EditorFor(model => model.BeneficiareEnfants[i - 1].DateNaissance, new { htmlAttributes = new { #class = "form-control" } })#Html.ValidationMessageFor(model => model.BeneficiareEnfants[i - 1].DateNaissance, "", new { #class = "text-danger" })</td>
</tr>
}
</tbody>*#
</table>
</div>
</div>
<div class="card-header custom-card-header">
<h4>Bénéficiaire (s) en cas de décès : </h4>
</div>
<div class="row">
#*#for (int i = 0; i < 4; i++)
{
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.BeneficiareEnCas[i].Prenom)
#Html.EditorFor(model => model.BeneficiareEnCas[i].Prenom, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.BeneficiareEnCas[i].Prenom, "", new { #class = "text-danger" })
</div>
}*#
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.FaitA)
#Html.EditorFor(model => model.FaitA, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.FaitA, "", new { #class = "text-danger" })
</div>
<div class="col-sm-6">
<div class="form-group">
#Html.LabelFor(model => model.FaitLe)
#Html.EditorFor(model => model.FaitLe, new { htmlAttributes = new { #class = "form-control" } })
</div>
#Html.ValidationMessageFor(model => model.FaitLe, "", new { #class = "text-danger" })
</div>
</div>
</div>
<input type="submit" value="Create" class="btn btn-info" />
</div>
}
As you can see in the "controller", i'm only saving the data of the simple properties, but if you notice in the view there is a comment table, that table contains a list of "BeneficiaireConjoint" and "BeneficiaireEnfant", the two properties are properties of "BulletinAdhesionRMA" but they are types of List.
So far so good, but when i try this code in my controller it doesn't work.
public class BulletinAdhesionRMAController : Controller
{
public BulletinAdhesionDbContext db = new BulletinAdhesionDbContext();
// GET: BulletinAdhesionRMA
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "" )] BulletinAdhesionRMA bulletinAdhesionRMA)
{
if(ModelState.IsValid)
{
db.BulletinAdhesionsRMA.Add(bulletinAdhesionRMA);
db.BeneficiaireConjoints.Add(bulletinAdhesionRMA.BeneficiareConjoints);
db.BeneficiaireEnfants.Add(bulletinAdhesionRMA.BeneficiareEnfants);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View();
}
}
I don't know how to handle that list from the controller nor the view with razor.
I would really appreciate some ideas.
Thank you in advance.

Asp.net MVC - input type="file" validation error

i create a form that have 2 input text and 1 input file, when i selected the image and click on submit button an error occurs for the input file
i don't have any validation on input file!
this is my view code:
#model Test.Models.Domain.tblCategory
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEditeCat", "Admin", FormMethod.Post, new {enctype="multipart/form-data",onsubmit="return SubmitCatForm(this)" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.id)
#Html.HiddenFor(model => model.Pic)
<div class="form-group">
#Html.Label("Title", new { #class = "control-label" })
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title)
</div>
<div class="form-group">
#Html.Label("Text", new { #class = "control-label" })
#Html.EditorFor(model => model.Text, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="form-group">
#Html.LabelFor(model=>model.Pic, new { #class = "control-label" })
<img src="#Url.Content(Model.Pic)" style="margin:10px" height="150" width="150" id="imagePreview" />
<input type="file" id="ImageUpload" name="ImageUpload" accept="image/jpeg,image/png" onchange="ShowImagePreview(this,document.getElementById('imagePreview'))" />
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn btn-primary btn-danger" />
</div>
}
and this is my model:
public partial class tblCategory
{
public int id { get; set; }
[Required(ErrorMessage = "*")]
public string Title { get; set; }
public string Text { get; set; }
[DisplayName("Image")]
public string Pic { get; set; }
public HttpPostedFileBase ImageUpload { get; set; }
public tblCategory()
{
Pic = "~/Cntent/upload/img/cat/defalt.png";
}
}

Why all fields are required when using ASP.NET EF6 auto created controller and view

I am new to ASP.NET EF6 and need some help here, I created a datamodel and a datacontext
public class RepositoryDbContext : DbContext
{
public RepositoryDbContext()
: base("DefaultConnection")
{
}
public DbSet<Repository> Repositories { get; set; }
}
public class Repository
{
public int ID { get; set; }
public string SKU { get; set; }
public string Title { get; set; }
}
and the html page
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Order</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.SKU, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SKU, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SKU, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", 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>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Then I used Visual Studio 2015 to auto create the controller and views, but in the create page, the sku and title are both required, how could I get rid of the required validation for Title field.
Thanks very much, I tried googling it but no luck.

MVC 5 Validation Error messages not appearing

I have a problem where the validation messages are not appearing for a given form. The form appears inside a jQuery modal dialog, which is opened when you click a button on the main page.
When I try submitting the form with all fields empty, I should get errors that such and such fields are required, but I don't. However, if I debug and go into the Controller code to see what Model is being reported as invalid, I see the messages mentioned here, that such and such fields are required.
I have tried removing the custom JavaScript being used in the view when Submit is done, but that doesn't solve the problem.
This is the model:
public class Expense : ActivityLog
{
[Key]
public int ID { get; set; }
public bool chargedBySeller { get; set; }
public string chargingEntity { get; set; }
[Required]
public string chargeCurrency { get; set; }
[Required]
public double chargeAmount { get; set; }
public DateTime chargeDate { get; set; }
public bool countInExpensesTotalling { get; set; }
[Required]
public string paymentMethod { get; set; }
public List<Refund> refundsDoneForThisCharge { get; set; }
}
This is the controller:
public class PurchasesController : Controller
{
private AppDbContext db = new AppDbContext();
//Other Actions removed for brevity
[HttpPost]
public ActionResult AddOrEditExpense(Expense expense)
{
if (ModelState.IsValid)
{
if (Session["expensesList"] == null)
{
Session["expensesList"] = new List<Expense>();
}
if ((int)Session["expenseAddEditMode"] == 2) //ADD
{
((List<Expense>)Session["expensesList"]).Add(expense);
}
else if ((int)Session["expenseAddEditMode"] == 1) //EDIT
{
((List<Expense>)Session["expensesList"])[(int)Session["expenseEditIndex"]] = expense;
}
}
return PartialView("~/Views/Purchases/Expense/ViewList.cshtml", Session["expensesList"]);
}
}
Finally, this is the Razor View code:
<script type="text/javascript">
$(function () {
$("#add-or-edit-expense-form").on("submit", function (e) {
e.preventDefault();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
$("#expense-list-div").html(data);
$("#expense-dialog").dialog("close");
}
});
});
});
</script>
#model ExpOrderBluManagement_Web.Models.ApplicationModels.Expense
#using (Html.BeginForm("AddOrEditExpense", "Purchases", FormMethod.Post, new { id = "add-or-edit-expense-form" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Expense</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.chargedBySeller, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.chargedBySeller)
#Html.ValidationMessageFor(model => model.chargedBySeller, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.chargingEntity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.chargingEntity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.chargingEntity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.chargeCurrency, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.chargeCurrency, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.chargeCurrency, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.chargeAmount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.chargeAmount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.chargeAmount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.chargeDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.chargeDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.chargeDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.countInExpensesTotalling, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.countInExpensesTotalling)
#Html.ValidationMessageFor(model => model.countInExpensesTotalling, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.paymentMethod, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.paymentMethod, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.paymentMethod, "", 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>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
As #Stephen sad if you dynamically add controls to the DOM, you must reparse the validator. Try writing your script like this:
<script type="text/javascript">
$(function () {
var $form = $("#add-or-edit-expense-form");
$.validator.unobtrusive.parse($form);
$form.on("submit", function (e) {
e.preventDefault();
if($form.valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
$("#expense-list-div").html(data);
$("#expense-dialog").dialog("close");
}
});
}
});
});
</script>
adding this $.validator.unobtrusive.parse($form); Also, I would check if form is valid and then do the ajax call.
You have jQuery Val at bottom of page, do you have a link to jQuery in head

Resources