keep selected item of dropdownlist as you move from page to page in a webgrid - asp.net-mvc-4

I have a page that has a dropdownlist and a webgrid. The webgrid has pagenumbers. If I am on page 1 and I select page 2 the item
selected on the dropdown is lost and goes back to "Select Branch"
I want to be able to keep the item selected as I move from page to page. How do I do that? I tried the request.form but did not work
public ActionResult Index()
{
var currentUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();
Edmviewmodel objedmtest = new Edmviewmodel();
string ddlState_SelectedStateValue = Request.Form["ddlDropDownList"];
if (currentUser != null)
{
try
{
objedmtest = _edmDataService.GetRequiredData("A05");
ViewData["SelectList"] = HttpContext.Session["SelectList"] ?? new List<string>();
}
catch (Exception ex)
{
//logger.Error(ex);
}
}
return View(objedmtest);
}
Here is the html code.
#{
var grid = new WebGrid(source: Model.GetCatDataByLocation,
defaultSort: "CustomerName",
canSort: true,
rowsPerPage: 5
);
}
<div>
<div>
<label for="ddlBranch">Branch:</label>
#Html.DropDownList("ddlDropDownList", Model.BranchesSelectList, "Select Branch", new { #class = "css-class" })
</div>
<div>
#grid.GetHtml(
tableStyle: "grid",
headerStyle: "head",
alternatingRowStyle: "alt",
columns: grid.Columns(
grid.Column("Select", format: #<text><input name="CustomerName" type="checkbox" value="#item.CustomerName" #Html.Raw(((List<string>)ViewData["SelectList"]).Contains(#item.CustomerName) ? "checked" : "") /></text>),
grid.Column("CustomerName", "CustomerName"),
grid.Column("CustomerNumber", "CustomerNumber"),
grid.Column("Orderdate", "Orderdate", canSort: false),
grid.Column("OrderNumber", "OrderNumber"),
grid.Column("Routenumber", "Routenumber"),
grid.Column("Primaryrep", "Primaryrep"),
grid.Column("Isvalidated", "Isvalidated")
)
)
</div>
<div>
</div>
</div>

<script type="text/javascript">
$(document).ready(function () {
//check for existance of query string
var urlg = window.location.href; //global url
var previousIndex = 0;
if (urlg.indexOf("ap") > 0) {
previousIndex = (urlg.substring(urlg.indexOf("ap=") + 3));
}
$('select>option:eq(' + previousIndex + ')').prop('selected', true); //zero-based
$("a").click(function (event) {
$("td a").each(function () {
var old = $(this).attr('href');
idx = $("select[name='ddlDropDownList'] option:selected").index();
$(this).attr("href", old + "&ap=" + idx);
});
});
});
</script>

Related

MVC displaying and updating picture from byte

I am trying to add an editing function to a DB record that a user submitted. The thing is, that there is a picture (as byte) in the mix. The picture has previously been cropped (mainly for styling reasons) and of course, a user would need to have the option to a) keep the existing picture or b) select and crop a new picture. The following code works fine if a user submits a new picture, but in case there is no new picture, it would override the existing one instead of keeping the one the user previously uploaded.
Here's my controller:
// POST: EditErrand
public ActionResult UpdateErrand([Bind(Exclude = "Picture")]EditErrandsViewModel model)
{
string newPic = Request.Form["editErrandCroppedPicture"];
byte[] imageBytes = Convert.FromBase64String(newPic);
var userId = User.Identity.GetUserId();
var errand = new EditErrandsViewModel
{
ID = model.ID,
UserID = User.Identity.GetUserId(),
FirstName = UserManager.FindById(userId).FirstName,
Email = UserManager.FindById(userId).Email,
Phone = UserManager.FindById(userId).PhoneNumber,
Hometown = UserManager.FindById(userId).Hometown,
Rating = model.Rating,
Category = model.Category,
SubCategory = model.SubCategory,
Title = model.Title,
Description = model.Description,
Location = model.Location,
ASAP = model.ASAP,
StartDateTime = model.StartDateTime,
DurationInHours = model.DurationInHours,
EndDateTime = model.EndDateTime,
DateTimePosted = DateTime.UtcNow.ToUniversalTime(),
Currency = model.Currency,
Offering = model.Offering,
Price = model.Price,
errandTax = model.errandTax,
PaymentMethod = model.PaymentMethod,
LatitudePosted = model.LatitudePosted,
LongitudePosted = model.LongitudePosted,
LocationPosted = model.LocationPosted,
UserActivityLatitude = model.LatitudePosted,
UserActivityLongitude = model.LongitudePosted,
UserActivityLocation = model.LocationPosted,
Published = false
};
if (imageBytes.Length > 2)
{
errand.Picture = imageBytes;
}
DB.Entry(errand).State = EntityState.Modified;
DB.SaveChanges();
var Success = new UserActivities
{
ActivityName = "EditErrand_Success",
UserID = User.Identity.GetUserId(),
ActivityTimeStamp = DateTime.Now.ToUniversalTime(),
ActivityLatitude = model.UserActivityLatitude,
ActivityLongitude = model.UserActivityLongitude,
ActivityLocation = model.UserActivityLocation
};
DB.UserActivityList.Add(Success);
DB.SaveChanges();
return RedirectToAction("errandPreview");
}
The controller has the following statement in there because if a user does not upload a file, it would still write 0x to the DB.
if (imageBytes.Length > 2)
{
errand.Picture = imageBytes;
}
For the sake of completeness I have added the relevant part of the view as well, so you get an idea on how cropping (using JCrop) is done:
<div id="editErrandPictureDisplay" class="errandomDisplay col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-4 col-md-7 col-lg-offset-5 col-lg-6">
<img id="editErrandPicture" class="editErrandPicture" src="#Url.Action("errandPicture", "errandom")" />
</div>
<div id="editErrandPictureArea" class="manageArea row">
#Html.LabelFor(m => m.Picture, new { #id = "editErrandPictureLabel", #class = "manageLabel col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-3 col-lg-offset-1 col-lg-4" })
<a id="editErrandPictureSelectionButton" class="manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-0 col-md-7 col-lg-offset-0 col-lg-6" href="#">
select a file...
</a>
#Html.TextBoxFor(m => m.Picture, new { #id = "editErrandPictureField", #class = "manageField col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-0 col-md-7 col-lg-offset-0 col-lg-6", #type = "file", #style = "display: none" })
</div>
<hr />
<script>
jQuery("#editErrandPictureSelectionButton").click(function () {
$("#editErrandPictureField").click();
$("#editErrandCroppingArea").show();
});
</script>
<script>
$("#editErrandPictureField").change(function () {
var fullFileName = $("#editErrandPictureField").val()
$("#editErrandPictureSelectionButton").html(fullFileName.substr(fullFileName.lastIndexOf('\\') + 1));
});
</script>
<div id="editErrandCroppingArea" class="manageArea row" style="display: none">
<img id="editErrandOriginal" class="editErrandImage" src="" alt="" style="display: none" />
<canvas id="editErrandCropped" class="editErrandImage" height="5" width="5"></canvas>
<input id="editErrandButtonCrop" class="manageButton col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-10 col-lg-offset-1 col-lg-10" type="button" value="Crop" />
<input id="editErrandCropX" class="editErrandData" name="editErrandCropX" type="hidden" />
<input id="editErrandCropY" class="editErrandData" name="editErrandCropY" type="hidden" />
<input id="editErrandCropW" class="editErrandData" name="editErrandCropW" type="hidden" />
<input id="editErrandCropH" class="editErrandData" name="editErrandCropH" type="hidden" />
<input id="editErrandCroppedPicture" class="editErrandData" name="editErrandCroppedPicture" type="hidden" />
</div>
<script type="text/javascript">
$(function () {
if ($('#editErrandCroppingArea').width() > 500) {
$('#editErrandPictureField').change(function () {
$('#editErrandOriginal').hide();
var reader = new FileReader();
reader.onload = function (e) {
$('#editErrandOriginal').show();
$('#editErrandOriginal').attr("src", e.target.result);
$('#editErrandOriginal').Jcrop({
onChange: SetCoordinates,
onSelect: SetCoordinates,
aspectRatio: 1,
boxWidth: 450,
addClass: 'editErrandCropping'
});
}
reader.readAsDataURL($(this)[0].files[0]);
});
}
else {
$('#editErrandPictureField').change(function () {
$('#editErrandOriginal').hide();
var reader = new FileReader();
reader.onload = function (e) {
$('#editErrandOriginal').show();
$('#editErrandOriginal').attr("src", e.target.result);
$('#editErrandOriginal').Jcrop({
onChange: SetCoordinates,
onSelect: SetCoordinates,
aspectRatio: 1,
boxWidth: 250,
addClass: 'editErrandCropping'
});
}
reader.readAsDataURL($(this)[0].files[0]);
});
}
$('#editErrandButtonCrop').click(function () {
var x1 = $('#editErrandCropX').val();
var y1 = $('#editErrandCropY').val();
var height = $('#editErrandCropH').val();
var width = $('#editErrandCropW').val();
var canvas = $("#editErrandCropped")[0];
var context = canvas.getContext('2d');
var img = new Image();
img.onload = function () {
canvas.height = height;
canvas.width = width;
context.drawImage(img, x1, y1, width, height, 0, 0, width, height);
var image = canvas.toDataURL().replace(/^data:image\/[a-z]+;base64,/, "");
$('#editErrandCroppedPicture').val(image);
//$('#editErrandButtonUpload').show();
$('#editErrandCropped').hide();
$('#editErrandButtonCrop').hide();
};
img.src = $('#editErrandOriginal').attr("src");
});
});
function SetCoordinates(c) {
$('#editErrandCropX').val(c.x);
$('#editErrandCropY').val(c.y);
$('#editErrandCropW').val(c.w);
$('#editErrandCropH').val(c.h);
$('#editErrandButtonCrop').show();
};
</script>
So ultimately my question is:
How can I update the picture if a user selects a new one (which works fine) AND make sure the previously uploaded picture is not overridden if a user does not select a new picture? Right now, all values would be updated except for the picture (unless a new picture is selected and cropped).
Now after adding a View Model, I get the following error:
The entity type EditErrandViewModel is not part of the model for the current context.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.InvalidOperationException: The entity type EditErrandViewModel is not part of the model for the current context.
Source Error:
Line 348: errand.Picture = imageBytes;
Line 349: }
Line 350: DB.Entry(errand).State = EntityState.Modified;
Line 351: DB.SaveChanges();
Line 352: var Success = new UserActivities

JqWidget tabs - dynamically add tab with ajax content

I want create a dynamic on click append data to tab but I get in the tab undefined. Could you tell me whats wrong? Not quite sure what is the case,
My js
<script type="text/javascript">
$(document).ready(function () {
// Create jqxTabs.
$('#jqxTabs').jqxTabs({ width: 580, height: 200,showCloseButtons: true });
var length = $('#jqxTabs').jqxTabs('length') + 1;
var loadPage = function (url) {
$.get(url, function (data) {
data;
// console.log( $('#content' + length ).text(data));
// console.log(data);
});
}
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
$('#jqxTabs').jqxTabs('addFirst', 'Sample title',loadPage(getvalue).text());
$('#jqxTabs').jqxTabs('ensureVisible', -1);
});
// $('#jqxTabs').on('selected', function (event) {
// var pageIndex = event.args.item + 1;
// loadPage('pages/ajax' + pageIndex + '.htm', pageIndex);
// });
});
</script>
My html
<div class="s">
<span rel="gen.php">Load</span>
</div>
<div id='jqxWidget'>
<div id='jqxTabs'>
<ul>
</ul>
</div>
</div>
So first check the right syntax for tab control:
HTML:
....
<div id='jqxTabs'>
<ul>
<li></li>
</ul>
<div></div>
</div>
Javascript:
// Create jqxTabs.
$('#jqxTabs').jqxTabs({ width: 580, height: 200, showCloseButtons: true });
$('#jqxTabs').jqxTabs("removeFirst"); //here removes the empty tab
//here the function must return the content, and the ajax must be async false for this purpose
var loadPage = function (url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
$('#jqxTabs').jqxTabs('addFirst', 'Sample title', loadPage(getvalue));
$('#jqxTabs').jqxTabs('ensureVisible', -1);
});
For better understanding check: http://jsfiddle.net/charlesrv/h4573ykv/1/
EDIT: For the new condition, use a custom attribute so checking would be easier:
$('div.s span').click(function() {
var getvalue = $(this).attr('rel');
var opened = $(this).attr('opened');
if (!opened) {
$(this).attr('opened', true);
$('#jqxTabs').jqxTabs('addFirst', 'Sample title', loadPage(getvalue));
$('#jqxTabs').jqxTabs('ensureVisible', -1);
}
});

MVC4 WebGrid in dialog hangs in IE and no pagination in Chrome

MVC4: I am new to using WebGrid with MVC. Code below produces WebGrid inside dialog, but pagination does not work in Chrome ( blank page displayed) and in IE : dialog with WebGrid shown , but IE hangs (seem to be doing something and then hangs, no chance to try pagination even).
What is wrong with my code?
Thank you
HomeController.cs
public ActionResult MyReport (int id) // get here on click in SelectList
{
List<MyLocation> myl = MyLocation.GetAllLocations(31); // static method in MyLocation model
return View(myl);
}
public ActionResult MyLocationDetails (int id)
{
LocationDetails ld = new LocationDetails();
List<LocationDetails> model = ld.GetTestLocationDetails(); //model has 20 records
return PartialView(model); // MyLocationDetails partial view to be displayed in Dialog
}
MyReport.cshtml View that should display dialog
#model IEnumerable<MyLocation>
#Html.ActionLink("Location Details", "MyLocationDetails", null, new { id = 234 }, new { #class = "LocDetails" })
<div id="LocDetails-dialog"></div>
<script type="text/javascript">
$(function () {
$('#LocDetails-dialog ').dialog({
autoOpen: false,
width: 400,
resizable: false,
modal: true
});
$('.LocDetails').click(function() {
$('#LocDetails-dialog ').load(this.href, function() {
$(this).dialog('open');
});
return false;
});
});
</script>
MyLocationDetails.cshtml
#model List
<div>
#if (Model != null)
{
if (Model.Count != 0)
{
<div id="divLocDetails">
#{WebGrid grid = new WebGrid(source: Model,
rowsPerPage: 5,
canPage: true
);
grid.SortDirection = SortDirection.Ascending;
}
#grid.GetHtml(
htmlAttributes: new { id = "LocDetails" },
mode: WebGridPagerModes.All,
firstText: "First",
previousText: "Prev",
nextText: "Next",
lastText: "Last",
columns: new[] {
grid.Column("city", header: "City", canSort: true),
grid.Column("country", header: "Country", canSort: false)
}
)
</div>
}
else
{
<label>No results</label>
}
}
</div>

cannot remove knockout observableArray item with SingalR

I am struggling with two issues. The first one is that after I pushed a new item into observableArray and try to refresh the accordion. The new item did not show up in the accordion. But the producs().length increased by one.
this.hub.client.productAdded = function (p) {
products.push(new productListViewModel(p.id, p.Name, self));
$("#accordion").accordion("refresh");
//loadAccordion();
};
My second issue is that After SignalR deleted an item in the database and returned with the deleted object I tried to remove the deleted object from the observableArray. I have tried different ways and none of them work.
this.hub.client.productRemoved = function (deleted) {
//var deleted = ko.utils.arrayFilter(products(), function (item) {
// return item.id == deleted.id;
//})[0];
products.remove(function (item) { return item.id == deleted.id; });
//products.remove(deleted);
$("#accordion").accordion("refresh");
};
What do I miss here? Below is the whole page code for reference
#{
ViewBag.Title = "SignalR";
}
<h2>SignalR</h2>
<div id="error"></div>
<h2>Add Product</h2>
<form data-bind="submit: addProduct">
<input data-bind="value: newProductText" class="ui-corner-all" placeholder="New product name?" />
<input type="submit" class="ui-button" value="Add Product" />
</form>
<h2>Our Products</h2>
listed: <b data-bind="text: productCount"></b> product(s)
#*<div id="accordion" data-bind="template: {name: productTemplate, foreach: products }, visible: products.Length > 0"></div>*#
<div id="accordion" data-bind='template: {name: "product-template", foreach: products }'></div>
<script type="text/html" id="product-template">
<h3 data-bind="text: name"></h3>
<div>
<input type="button" class="ui-button" value="Remove Rroduct" data-bind="click: removeProduct" />
</div>
</script>
<span data-bind="visible: productCount() == 0">What? No products?</span>
#section Scripts {
#Scripts.Render("~/bundles/knockout")
#Scripts.Render("~/bundles/signalr")
<script src="/Scripts/jquery.signalR-2.0.1.min.js" type="text/javascript"></script>
<script src="~/signalr/hubs" type="text/javascript"></script>
<script src="/Scripts/jquery.livequery.min.js"></script>
<style>
#accordion {width: 300px;}
#accordion h3 { padding-left: 30px}
</style>
<script>
function productViewModel(id, name, ownerViewModel) {
this.id = ko.observable(id);
this.name = ko.observable(name);
var self = this;
this.removeProduct = function () { ownerViewModel.removeProduct( id); };
this.name.subscribe(function (newValue) {
ownerViewModel.updateProduct(ko.toJS(self));
});
}
function productListViewModel() {
this.hub = $.connection.products;
this.products = ko.observableArray([]);
this.newProductText = ko.observable();
chat = this.hub
var products = this.products;
var self = this;
// Get All
this.init = function () {
this.hub.server.getAll();
}
this.hub.client.productAll = function (allProducts) {
//var mappedProducts = $.map(allProducts, function (item) {
// return new productViewModel(item.id, item.name, self);
//});
//products(mappedProducts);
$.each(allProducts, function (index, item) {
products.push(new productViewModel(item.id, item.Name, self));
});
loadAccordion();
};
this.hub.reportError = function (error) {
$("#error").text(error);
};
$.connection.hub.error(function (error) {
console.log('SignalR error: ' + error)
});
this.hub.client.productAdded = function (p) {
products.push(new productListViewModel(p.id, p.Name, self));
$("#accordion").accordion("refresh");
//loadAccordion();
};
this.hub.client.productRemoved = function (deleted) {
//var deleted = ko.utils.arrayFilter(products(), function (item) {
// return item.id == deleted.id;
//})[0];
products.remove(function (item) { return item.id == deleted.id; });
//products.remove(deleted);
$("#accordion").accordion("refresh");
};
// Commands
this.addProduct = function () {
var p = { "Name": this.newProductText() };
this.hub.server.add(p).done(function () { }).fail(function (e) { alert(e); });
this.newProductText("");
};
this.removeProduct = function (id) {
this.hub.server.remove(id).done(function () { alert("aa"); }).fail(function (e) { alert(e+" aa"); });
};
this.productCount = ko.dependentObservable(function () {
return products().length;
}, this);
}
function loadAccordion() {
$("#accordion").accordion({ event: "mouseover" });
}
$(function () {
var viewModel = new productListViewModel();
ko.applyBindings(viewModel);
// connect SinalR
$.connection.hub.start(function () { viewModel.init(); });
//$.connection.hub.start(function () { chat.server.getAll(); });
});
</script>
}
To solve your add problem: you are creating a new productListViewModel but you need to add a new productViewModel, so you just need to create the correct viewmodel:
this.hub.client.productAdded = function (p) {
products.push(new productViewModel(p.id, p.Name, self));
$("#accordion").accordion("refresh");
};
To solve your delete problem: in your productViewModel the id is a ko.observable so you need to write item.id() to access its value in the remove function:
this.hub.client.productRemoved = function (deleted) {
products.remove(function (item) { return item.id() == deleted.id; });
$("#accordion").accordion("refresh");
};

Add error message if duplicate record exist in MVC Popup Form

I have a popup window called AddNew will display when the user click a button called add New. The button itself has number of field called TRN and DOB. The problem that i have now that i am trying to display error message when the user try to add duplicate TRN but unfortunately no error message display only if the required field is empty.
Is there anyway i could display the duplicate error message in validation summary like displaying in required field and hold all the previous entered value in the form. Please advise. Thank you
Here is the code that i have so far. Thank you
Index.cshtml
<input type="button" id="btnAddNew" style="height:50px; font-size:14px; width:95px; background-color:#3399FF; white-space: normal;" class="k-button" title="AddNew" value="Add New" />
<script type="text/javascript">
$(document).ready(function () {
$('#btnAddNew').click(function () {
window.open('#Url.Action("AddNew", "Details")', 'AddProduct', 'height=' + (window.screen.height - 450) + ',width=950,left=' + (window.screen.width - 5) + ',top=10,status=no,toolbar=no,resizable=yes,scrollbars=yes');
});
});
</script>
AddNew.cshtml (window popup)
#{
Layout = "~/Views/Shared/_LayoutNoMenu.cshtml";
}
<script src="../../Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
#model HHIMS_Web_App.Models.CModel
#{
ViewBag.Title = "New Product";
}
#using (Html.BeginForm("Create", "Details", FormMethod.Post, new { id = "frmAsset" }))
{
ViewContext.FormContext.ValidationSummaryId = "valSumId";
#Html.ValidationSummary(false, "Please fix the following errors:", new Dictionary<string, object> { { "id", "valSumId" } });
<fieldset id="AddNew">
<div>
<div class="addInfo">
#Html.LabelFor(model => model.TRN)
#Html.EditorFor(model => model.TRN)
#Html.ValidationMessageFor(model => model.TRN, "*")
</div>
<div class="AddSmallBox">
#Html.LabelFor(model => model.DOB)
#Html.EditorFor(model => model.DOB)
#Html.ValidationMessageFor(model => model.DOB, "*")
</div>
</div>
<div>
<div class="smallAddAndCancel">
<input type="button" id="btnCancel" style="height:50px; width:85px; font-size:14px; background-color:#3399FF" class="k-button" title="Cancel" value="Cancel" onclick="window.close()" />
<input type="submit" id="btnSave" style="height:50px; width:85px; font-size:14px; background-color:#3399FF;white-space: normal" class="k-button" title="Save" value="Save"/>
</div>
</div>
</fieldset>
}
<script type="text/javascript">
$(document).ready(function () {
$("#datepicker").closest("span.k-datepicker").width(400);
$('#btnSave').click(function () {
var validation = $("#frmAsset");
if (!validation.valid()) {
return false;
else
{
$.ajax({
type: 'POST',
url: "#Url.Action("Create","Details")",
data: {
TRN: $("#TRN").val(),
DOB: $("#DOB").val(),
},
success: function () {
window.close()
}
});
}
});
});
</script>
Controller:
[HttpPost]
public ActionResult Create(Cmodel)
{
try
{
if (ModelState.IsValid)
{
CheckDuplicateHRNExist(model);
return RedirectToAction("AddNew");
}
if (ModelState.IsValid)
{
HH_DataAccessLayer.Consumers dalModel = new HH_DataAccessLayer.Consumers();
Mapper.CreateMap<CModel, HH_DataAccessLayer.Consumers>();
Mapper.Map(model, dalModel);
return RedirectToAction("Index");
}
}
catch (DbUpdateConcurrencyException e)
{
var entry = e.Entries.Single();
var clientValues = (CModel)entry.Entity;
}
return RedirectToAction("Index");
}
/// <summary>
/// Validate TRN find if no duplicate TRN recorded
/// </summary>
/// <param name="model"></param>
private void CheckDuplicateTRNExist(CModel model)
{
HEntities context = new HEntities();
if (model.TRN != null)
{
var duplicateTRN = context.Consumers.Where(d => d.TRN == model.TRN).FirstOrDefault();
if (duplicateTRN != null)
{
var errorMessage = String.Format("TRN is already exist.", duplicateTRN);
ModelState.AddModelError(string.Empty, errorMessage);
}
}
}
Model
[Required(ErrorMessage = "Please enter TRN")]
[DisplayName("TRN")]
[StringLength(20)]
public string TRN { get; set; }
[Required(ErrorMessage = "Please enter or select Date of Birth")]
[DisplayName("Date Of Birth")]
public DateTime? DOB { get; set; }
If I'm not mistaking, ValidationSummary must be set to true to display custom errors.
Edit: to be complete:
In your AddNew.cshtml file, replace
#Html.ValidationSummary(false, "Please fix the following errors:", new Dictionary<string, object> { { "id", "valSumId" } });
With:
#Html.ValidationSummary(true, "Please fix the following errors:", new Dictionary<string, object> { { "id", "valSumId" } });