I'm having a really tough time doing something that should be very simple. I've been away from ASP.NET for a couple of years now and some of the 4.x stuff is new to me. I just can't get it working right and could use some pointers, please.
I'm not using MVC and it's not an option, on this project. I'm using a FormView in a web form. The project has an edmx in a separate class library. One of my entities is bound to the FormView. I'm extending my model using annotations, for validation.
Here is my extended entity with validation attributes:
namespace DataAccess.Model
{
[MetadataType(typeof(DataAccess.Model.NoBillingMetadata))]
public partial class NoBilling {}
public partial class NoBillingMetadata
{
[Required(ErrorMessage="Company is required."),
StringLength(50, ErrorMessage="Company cannot be greater than 50 characters.")]
public string Company
{
get;
set;
}
[Required(ErrorMessage="Email Domain is required."),
StringLength(50, ErrorMessage="Email Domain cannot be greater than 50 characters.")]
public string EmailDomain
{
get;
set;
}
}
}
Here's a portion of the web form (has a master page associated with it):
protected void NoBillingFormView_Init(object sender, EventArgs e)
{
List<NoBilling> nbList = new List<NoBilling>();
nbList.Add(new NoBilling());
this.NoBillingFormView.DataSource = nbList.AsQueryable();
this.NoBillingFormView.DataBind();
}
...and...
protected void SaveButton_Click(object sender, EventArgs e)
{
//get bound entity
NoBilling nb = this.NoBillingFormView.DataItem as NoBilling;
//validation output results
ICollection<ValidationResult> results = new List<ValidationResult>();
//validate entity
bool valid = DataValidator.TryValidate(nb, out results);
//save
try
{
if (valid)
{
NoBillingProxy nbPx = new NoBillingProxy();
nbPx.Save(nb);
}
else
{
//display validation errors
ValidationError validationError = new ValidationError(results);
validationError.Display();
}
}
catch (Exception exp)
{
//catch and log exception
}
}
The validation class that I'm calling above:
public class ValidationError : IValidator
{
ICollection<ValidationResult> _results = null;
string _validationMessage = null;
public ValidationError(ICollection<ValidationResult> results)
{
//loop through results and build message
this._results = results;
//construct message to display
this.BuildValidationMessage();
//assign formatted message to internal value
ErrorMessage = this._validationMessage;
IsValid = false;
}
public string ErrorMessage
{
get; set;
}
public bool IsValid
{
get; set;
}
public void Validate()
{
}
public void Display()
{
//get context of current page
Page currentPage = HttpContext.Current.Handler as Page;
//add custom validation message to page
currentPage.Validators.Add(new ValidationError(this._results));
}
private void BuildValidationMessage()
{
StringBuilder sb = new StringBuilder();
//error message header
sb.Append("At least one field was entered incorrectly. Please correct the following errors.");
sb.Append("<br />");
foreach (ValidationResult vr in this._results)
{
sb.Append("·");
sb.Append(vr.ErrorMessage);
sb.Append("<br />");
}
this._validationMessage = sb.ToString();
}
}
I can get parts working and other parts...not. The way it's coded above - the data binds, it's validated correctly, but the NoBilling entity retrieved from the FormView in the SaveButton_Click event handler, does not retain any input values from the form.
When I bound the data in Page_Load, it also would not retain the values...because a new, blank entity would be bound every time, wiping out any input. When I surrounded the binding code with if (!Page.IsPostBack), the entity is null when the form is posted,
throwing a NullReferenceException.
I'm confused and at wits end, at this point. Can someone help straighten me out here and point me in the right direction? I'm not finding good, reliable info on these topics so all of this is stitched together from Googling and forum posts.
zambizzi
Member
38 Points
28 Posts
ASP.NET 4.5 - Model Binding and manual validation problems
Oct 10, 2012 07:34 PM|LINK
I'm having a really tough time doing something that should be very simple. I've been away from ASP.NET for a couple of years now and some of the 4.x stuff is new to me. I just can't get it working right and could use some pointers, please.
I'm not using MVC and it's not an option, on this project. I'm using a FormView in a web form. The project has an edmx in a separate class library. One of my entities is bound to the FormView. I'm extending my model using annotations, for validation.
Here is my extended entity with validation attributes:
namespace DataAccess.Model { [MetadataType(typeof(DataAccess.Model.NoBillingMetadata))] public partial class NoBilling {} public partial class NoBillingMetadata { [Required(ErrorMessage="Company is required."), StringLength(50, ErrorMessage="Company cannot be greater than 50 characters.")] public string Company { get; set; } [Required(ErrorMessage="Email Domain is required."), StringLength(50, ErrorMessage="Email Domain cannot be greater than 50 characters.")] public string EmailDomain { get; set; } } }Here's a portion of the web form (has a master page associated with it):
The code-behind:
protected void NoBillingFormView_Init(object sender, EventArgs e) { List<NoBilling> nbList = new List<NoBilling>(); nbList.Add(new NoBilling()); this.NoBillingFormView.DataSource = nbList.AsQueryable(); this.NoBillingFormView.DataBind(); } ...and... protected void SaveButton_Click(object sender, EventArgs e) { //get bound entity NoBilling nb = this.NoBillingFormView.DataItem as NoBilling; //validation output results ICollection<ValidationResult> results = new List<ValidationResult>(); //validate entity bool valid = DataValidator.TryValidate(nb, out results); //save try { if (valid) { NoBillingProxy nbPx = new NoBillingProxy(); nbPx.Save(nb); } else { //display validation errors ValidationError validationError = new ValidationError(results); validationError.Display(); } } catch (Exception exp) { //catch and log exception } }The validation class that I'm calling above:
public class ValidationError : IValidator { ICollection<ValidationResult> _results = null; string _validationMessage = null; public ValidationError(ICollection<ValidationResult> results) { //loop through results and build message this._results = results; //construct message to display this.BuildValidationMessage(); //assign formatted message to internal value ErrorMessage = this._validationMessage; IsValid = false; } public string ErrorMessage { get; set; } public bool IsValid { get; set; } public void Validate() { } public void Display() { //get context of current page Page currentPage = HttpContext.Current.Handler as Page; //add custom validation message to page currentPage.Validators.Add(new ValidationError(this._results)); } private void BuildValidationMessage() { StringBuilder sb = new StringBuilder(); //error message header sb.Append("At least one field was entered incorrectly. Please correct the following errors."); sb.Append("<br />"); foreach (ValidationResult vr in this._results) { sb.Append("·"); sb.Append(vr.ErrorMessage); sb.Append("<br />"); } this._validationMessage = sb.ToString(); } }I can get parts working and other parts...not. The way it's coded above - the data binds, it's validated correctly, but the NoBilling entity retrieved from the FormView in the SaveButton_Click event handler, does not retain any input values from the form. When I bound the data in Page_Load, it also would not retain the values...because a new, blank entity would be bound every time, wiping out any input. When I surrounded the binding code with if (!Page.IsPostBack), the entity is null when the form is posted, throwing a NullReferenceException.
I'm confused and at wits end, at this point. Can someone help straighten me out here and point me in the right direction? I'm not finding good, reliable info on these topics so all of this is stitched together from Googling and forum posts.
Thanks!
zambizzi
Member
38 Points
28 Posts
Re: ASP.NET 4.5 - Model Binding and manual validation problems
Oct 16, 2012 07:59 PM|LINK
No takers? I didn't want to bump this, but I find it hard to believe no one else has attempted this! Any help would be much appreciated.