MVC 5 Validation Error messages not appearing - asp.net

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

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

JSON with AJAX not returning value in ASP.NET MVC

Good day guys,
I have a view that i need to search for customer Account details first and not reloading the page.
The user enters the customer Account number and then press the search button.
I have implemented below but it keeps throwing the error part that account number not exist.
// This is the View
#model CreditFacility_Web.Models.CreditFacilityModel.Transaction
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="w3-container" style="padding-left:60px">
#{
ViewBag.Title = "Credit Transaction";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Credit Transaction</h2>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Account_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Account_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Account_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button value="Search" class="btn btn-primary">Search</button>
</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.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Account_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Account_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Account_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Old_Balance, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Old_Balance, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Old_Balance, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Amount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Amount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.New_Balance, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.New_Balance, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.New_Balance, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Transaction_Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Transaction_Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Transaction_Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Narration, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Narration, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Narration, "", 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-success" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$(".btn-primary").click(function () {
var accNo = $('#Account_Number').val();
$.ajax({
url: "#Url.Action("AccountDetails", "Transactions")",
type: "POST",
dataType: "json",
data: { accountNo : accNo },
async: false,
error: function () {
alert('Account Number do not Exist Or Other Errors Occurred');
},
success: function (data) {
if (Object.keys(data).length > 0) {
$('#Firstname').val(data.Firstname);
$('#Old_Balance').val(data.Account_Balance);
}
}
});
});
});
</script>
}
Below is the Controller
[HttpPost]
public JsonResult AccountDetails(string accountNo)
{
using (CreditFacilityContext dataContext = new CreditFacilityContext())
{
var accSearchParameter = new SqlParameter("#Account_Number", accountNo);
var accDetails = dataContext.Database.SqlQuery<SavingsAccount>("spGetAccountDetails", accSearchParameter).Select(s => new SavingsAccount
{
Firstname = s.Firstname,
Account_Balance = s.Account_Balance,
//rest of properties
}).SingleOrDefault();
return Json(accDetails, JsonRequestBehavior.AllowGet);
}
}
First thing you want to do is remove that async: false. It does nothing other than tie up the main thread while the transaction is carried out.
I suggest checking that in the HTML that is generated, your input actually has the id of Account_Number and not an auto generated ID. You can manually set an ID of your choosing as well.
The JS should check the value of accNo before sending anything to the backend.

Can't create Model by View and Partialview updated using ajax

First of all sorry for my English.
My problem:
I've a table called Inspeccio and a related table called Criteris. The relation is ManyToMany so I've the table CriterisInspeccio.
I've a Model for these tables with the same name.
When I want to create a Inspeccio there's a Dropdownlist for different types of Inspeccio.
When I change the value of this Dropdownlist a list of Criteris is updated using ajax.
But when I submit the form the controller receive the InspeccioViewModel without the Criteris of the list.
The code:
InspecciosController:
// GET: Inspeccios/Create
public ActionResult Create()
{
ViewBag.IdTipusInspeccio = new SelectList(db.TipusInspeccio, "IdTipusInspeccio", "Tipus");
InspeccioViewModel inspeccioViewModel = new InspeccioViewModel();
return View(inspeccioViewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(InspeccioViewModel inspeccioViewModel)
{
if (ModelState.IsValid)
{
Inspeccio inspeccio = InspeccioHelper.ToInspeccio(inspeccioViewModel);
db.Inspeccio.Add(inspeccio);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(inspeccioViewModel);
}
public ActionResult CriterisSegonsTipusInspeccio(int idTipusInspeccio)
{
ICollection<CriterisInspeccioAssignatsViewModel> criteris = CriterisSegonsTipusInspeccioFalse(idTipusInspeccio);
return PartialView("CriterisInspeccioAssignatsViewModel", criteris);
}
Create view:
#model Inspeccions.ViewModels.InspeccioViewModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Inspeccio</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Clau, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Clau, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Clau, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DataCaducitat, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DataCaducitat, new { htmlAttributes = new { #class = "form-control date-picker" } })
#Html.ValidationMessageFor(model => model.DataCaducitat, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Data, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Data, new { htmlAttributes = new { #class = "form-control date-picker" } })
#Html.ValidationMessageFor(model => model.Data, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hora, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hora, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Hora, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Expedient, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Expedient, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Expedient, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IdTipusInspeccio, "Tipus", htmlAttributes: new {#class = "control-label col-md-2"})
<div class="col-md-10">
#Html.DropDownList("IdTipusInspeccio", null, new {htmlAttributes = new {#class = "form-control"}})
#Html.ValidationMessageFor(model => model.IdTipusInspeccio, "", new {#class = "text-danger"})
</div>
</div>
<div class="form-group" id="criteris"></div>
<div>
<br />
</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("Tornar al llistat d'inspeccions", "Index")
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#IdTipusInspeccio").change(function () {
var categoryId = $("#IdTipusInspeccio").val();
$("#criteris").load('#(Url.Action("CriterisSegonsTipusInspeccio", "Inspeccios", null, Request.Url.Scheme))?idTipusInspeccio=' + categoryId);
});
});
</script>
PartialView CriterisInspeccioAssignatsViewModel:
#model ICollection<Inspeccions.ViewModels.CriterisInspeccioAssignatsViewModel>
#using Inspeccions.Helpers
#foreach (var criteri in Model)
{
<div class="form-horizontal">
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(criter => criteri.Titol)
</dt>
<dd>
#Html.DisplayFor(criter => criteri.Titol)
</dd>
<dt>
#Html.DisplayNameFor(criter => criteri.Descripcio)
</dt>
<dd>
#Html.DisplayFor(criter => criteri.Descripcio)
</dd>
</dl>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.HiddenFor(criter => criteri.IdCriteri, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(criter => criteri.IdCriteri, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(criter => criteri.IdCriteri, "", new { #class = "text-danger" })
</div>
</div>
#if (#Html.Action() == "Create" || #Html.Action() == "Edit" || #Html.Action() == "CriterisSegonsTipusInspeccio")
{
<div class="form-group">
#Html.LabelFor(criter => criteri.Assignada, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(criter => criteri.Assignada)
#Html.ValidationMessageFor(criter => criteri.Assignada, "", new { #class = "text-danger" })
</div>
</div>
</div>
}
#if (#Html.Action() == "Details")
{
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(criter => criteri.Assignada)
</dt>
<dd>
#Html.DisplayFor(criter => criteri.Assignada)
</dd>
</dl>
}
</div>
<hr />
}
If I use it without ajax, having the Criteris fixed it works...
I've search it in Google and I can't find a solution for me.
Can you help me please?
Lot of thanks!
I've finally found the solution!
The problem comes from
public ActionResult CriterisSegonsTipusInspeccio(InspeccioViewModel inspeccioViewModel)
{
ICollection<CriterisInspeccioAssignatsViewModel> criteris = CriterisSegonsTipusInspeccioFalse(inspeccioViewModel.IdTipusInspeccio);
inspeccioViewModel.CriterisInspeccioViewModel = criteris;
return PartialView("CriterisInspeccioAssignatsViewModel", inspeccioViewModel);
}
It have to receive the Model :)

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.

Adding CheckBoxList of items to MVC 4 View

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>

Resources