ASP.NET MVC 2.0 Custom Client Validation - asp.net

I am trying to make a validator that will make sure that at least 2 items are selected. The validator works correctly on the server side but the client side code never gets executed.
Here is the code:
Sys.Mvc.ValidatorRegistry.validators["country"] = function (rule) {
var min = rule.ValidationParameters["min"];
return function (value, context) {
if (value >= min) return true;
return rule.ErrorMessage;
};
};
And here is the validator code:
public class CountryValidator : DataAnnotationsModelValidator<CustomValidations.CountryAttribute>
{
private int _minimum;
private string _message;
public CountryValidator(ModelMetadata metadata, ControllerContext context, CustomValidations.CountryAttribute attribute) : base(metadata,context,attribute)
{
_minimum = attribute.Minimum;
_message = attribute.ErrorMessage;
}
public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
{
var rule = new ModelClientValidationRule()
{
ErrorMessage = _message,
ValidationType = "country"
};
rule.ValidationParameters.Add("min", _minimum);
return new[] { rule };
}
}
I have even registered the validation adapter in global.asax file:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(AgeAttribute), typeof(AgeValidator));
DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(CountryAttribute),typeof(CountryValidator));
}
I am thinking that the validator only works with the elements that have a value property like textboxes etc.
UPDATE 1:
EnableClientValidation is invoked correctly and all the required JS files are included in the project. It seems like I need to attach the onblur to the context. I will try that and post the results.

<% =Html.EnableClientValidation(); %> needs to be in your view somewhere. Also make sure you reference MicrosoftAjax.js and MicrosoftMvcValidation.js in the same view (before your js function).

Either your missing MicrosoftMvcAjax.js or you need to implement your custom validation in jQuery as described on Mr. Haack's website http://haacked.com/archive/2009/11/19/aspnetmvc2-custom-validation.aspx.

I think it is because the default validation is invoked on the onblur event of the input textbox. And for a listbox this event was not being thrown.

Related

C# ASP.NET - Controlling/updating a textbox.text value through a class

Newbie here, I need help with a website I'm creating.
I have a class that does some analysis on some text that is input by the user, the class then finds an appropriate answer and sends it back to the textbox. (in theory)
Problem is I don't know how I can control and access the textbox on the default.aspx page from a class, all I get is "object reference is required non static field".
I made the textbox public in the designer file yet still no joy. :(
I've also read this: How can I access the controls on my ASP.NET page from a class within the solution? , which I think is along the lines of what I'm trying to achieve but I need clarification/step by step on how to achieve this.
Hope someone can point me in the right direction.
Many thanks,
Kal
This is the code I have added to the designer.cs file:
public global::System.Web.UI.WebControls.TextBox TextBox3;
public string MyTextBoxText
{
get
{
return TextBox3.Text;
}
set
{
TextBox3.Text = value;
}
}
This is the class method i have created:
public static cleanseMe(string input)
{
string utterance = input;
string cleansedUtt = Regex.Replace(utterance, #"[!]|[.]|[?]|[,]|[']", "");
WebApplication1._Default.TextBox3.text = cleansedUtt;
}
I could just return the cleansedUtt string i know, but is it possible for me to just append this string to the said textbox from this method, within this class?
I also tried it this way, i wrote a class that takes in the name of the textbox and string to append to that textbox. it works BUT only on the default.aspx page and does not recognise the textbox names within the difference classes. The code is as follows:
public class formControl
{
public static void ModifyText(TextBox textBox, string appendthis)
{
textBox.Text += appendthis + "\r\n";
}
I would suggest you that do not access the Page Controls like TextBox in your class. It will be more useful and a good practice that whatever functionality your class does, convert them into function which accept the parameters and returns some value and then on the basis of that value you can set the controls value.
So now you have reusable function that you can use from any of the page you want. You do not need to write it for every textbox.
Here I am giving you a simple example
public class Test
{
public bool IsValid(string value)
{
// Your logic
return true;
}
}
Now you can use it simple on your page like this
Test objTest = new Test();
bool result=objTest.IsValid(TextBox1.Text);
if(result)
{
TextBox1.Text="Everything is correct";
}
else
{
TextBox1.Text="Something went wrong";
}
If you have your class in the same project (Web Project) the following will work:
public class Test
{
public Test()
{
//
// TODO: Add constructor logic here
//
}
public static void ValidateTextBox(System.Web.UI.WebControls.TextBox txt)
{
//validation logic here
if (txt != null)
txt.Text = "Modified from class";
}
}
You can use this from your webform like this:
protected void Page_Load(object sender, EventArgs e)
{
Test.ValidateTextBox(this.txt);
}
If your class is in a different (class project), you would need to add a reference to System.Web to your project.

Passing parameters between asp.net webforms using PreviousPageType

I am trying to pass a few parameters between two web pages
within the source page I have the following properties
private string _testString { get; set; }
public string TestString
{
get
{
return _testString;
}
}
In previous msdn examples the return type was always set to a UI element (textbox.text)
However I am trying to pass the value from a dynamically generated link button which is why I chose to use the private accessor
In the click event of the link button on the source page I have the following:
protected void RenderReportInNewPage(LinkButton lb)
{
_testString = lb.CommandArgument.ToString();
Response.BufferOutput = true;
Response.Redirect("~/stuff/testviewer.aspx");
}
On the target page I have the source page referenced in the aspx as follows:
<%# PreviousPageType VirtualPath="~/stuff/testviewer.aspx"%>
And then in the codebehind of the target page I have the following:
Textbox.Text = PreviousPage.TestString;
PreviousPage displays the public property TestString but it is always null (as I don't think it is getting set but not sure why)
Is is possible to set a private accessor (_teststring) and have that value reflected within the public property? I'd appreciate any suggestions on what I have done wrong.
-Cheers
Found the error. It was not in the setting of the property but in how I was invoking the target page. In order to pass the properties across I needed to user Server.Transfer instead of Response.Redirect
protected void RenderReportInNewPage(LinkButton lb)
{
_testString = lb.CommandArgument.ToString();
Response.BufferOutput = true;
Server.Transfer("~/ReportBuilder/viewer.aspx");
}
-cheers

Constructor in webform?

I have an ASP.NET webform where I initialize an array with a list of controls on the page like this
FileUpload[4] = new FileUpload[4];
public myclass()
{
fileUpload[0] = FileUpload1;
fileUpload[0] = FileUpload2;
...etc
}
I then use these in the page load and they are all null. This seems a strange behavior to me. Can someone elaborate and explain? I can understand that they are null in the constructor but why should they be null when used in the page load.
They are null because the controls haven't been created yet.
Take a look at the ASP.NET Page Life Cycle Overview and the Init event.
If you want to add controls "manually", you need to do this in OnInit() so they can be given state from the LoadViewState() call that will happen just after OnInit().
If you don't know how many controls you need to add, because it's dynamic somehow, you can override LoadViewState and SaveViewState. See this example(written without Visual Studio):
public class MyPage : Page
{
class State
{
numberOfControls int
otherState object
}
override void LoadViewState(savedState object)
{
var myState = (State)savedState;
SetupMyControls(myState.numberOfControls);
base.LoadViewState(myState.otherState);
}
override object SaveViewState()
{
return new State
{
numberOfControls = GetNumberOfMyControls(),
otherState = base.SaveViewState()
};
}
}

ASP.NET Client Side Postback

I have your basic asp.net web form which contains some client-side JavaScript that forces the page to time out and then redirect after 5 minutes. Mainly to protect possibly sensitive information.
At timeout, I want to force a server post back allowing me to save the form values for future edits.
I have played with both ClientScript.GetPostBackClientHyperlink() and ClientScript.GetPostBackEventReference(). Both seem to cause EventValidation issues for me. Yes, I can turn off Event Validation but is there a different or better workaournd?
Ideally, I don’t want to invoke a control (which has to be displayed) but just cause a postback with some type of argument that I can recognize serverside as being the result of a timeout condition.
This may be overkill, but you could setup a javascript timer to fire a web service call. The .NET web service can accept the form data and save it.
No great solutions so I build my own. A pretty simple custom control. Comments welcome.
using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace BinaryOcean.Web.Library.WebControls
{
[ToolboxData("<{0}:PostBackTimer runat=\"server\" />"), DefaultProperty("Seconds"), DefaultEvent("Timeout")]
public class PostBackTimer : Control, IPostBackEventHandler
{
public PostBackTimer() { }
public string CommandArgument
{
get { return (string)ViewState["CommandArgument"] ?? string.Empty; }
set { ViewState["CommandArgument"] = value; }
}
public string CommandName
{
get { return (string)ViewState["CommandName"] ?? string.Empty; }
set { ViewState["CommandName"] = value; }
}
public bool Enabled
{
get { return (bool)(ViewState["Enabled"] ?? true); }
set { ViewState["Enabled"] = value; }
}
public int Seconds
{
get { return (int)(ViewState["Seconds"] ?? 0); }
set { ViewState["Seconds"] = value; }
}
[Description("PostBackTimer_OnTimeout")]
public event EventHandler Timeout = delegate { };
[Description("PostBackTimer_OnCommand")]
public event CommandEventHandler Command = delegate { };
public void RaisePostBackEvent(string eventArgument)
{
Timeout(this, EventArgs.Empty);
Command(this, new CommandEventArgs(CommandName, CommandArgument));
}
protected override void OnPreRender(EventArgs e)
{
if (Enabled && Seconds > 0)
{
var postback = Page.ClientScript.GetPostBackEventReference(this, null);
var script = string.Format("setTimeout(\"{0}\",{1});", postback, Seconds * 1000);
Page.ClientScript.RegisterStartupScript(GetType(), "PostBackTimer_" + UniqueID, script, true);
}
base.OnPreRender(e);
}
}
}
Couldn't you use a javascript timer to "click" the submit button? It sounds like using this form would be really annoying though, if it keeps posting back while you're trying to fill it out.
with javascript, call __doPostBack("clientIdOfSubmitButton", null). This will fire off a postback just as if that button (or any other control you want) had triggered it.

How do I convert an ASP.NET page using Ajax webmethods to an Ajax-enabled servercontrol?

In this tutorial I am reading, Dave Ward creates a page that shows the server date in a label without using the update panel.
I am trying to learn how to create servercontrols that use ajax for partial postbacks where methods within the control are called from clientscript generated by the same control, and I think that learning how to convert this page to a server control would be a help me understand what servercontrols use instead of webmethods to expose their methods to clientscript.
I created the page, codebehind, and javascript exactly as the article indicated and got the sample to work.
So, to start trying to convert this to a servercontrol, I moved Dave's Javascript for the page into a file, ~tests/JScript.js:
function UpdateTime() {
PageMethods.GetCurrentDate(OnSucceeded, OnFailed);
}
function OnSucceeded(result, userContext, methodName) {
$get('Literal1').innerHTML = result;
}
function OnFailed(error, userContext, methodName) {
$get('Literal1').innerHTML = "An error occured.";
}
And put the following class in my App_Code:
namespace foo
{
/// <summary>
/// Summary description for ServerControlTest
/// </summary>
public class ServerControlTest : CompositeControl, IScriptControl
{
ScriptManager sm;
protected override void OnPreRender(EventArgs e)
{
if (!this.DesignMode)
{
// Test for ScriptManager and register if it exists
sm = ScriptManager.GetCurrent(Page);
if (sm == null)
throw new HttpException("A ScriptManager control must exist on the current page.");
sm.RegisterScriptControl(this);
sm.EnablePageMethods = true;
}
base.OnPreRender(e);
}
protected override void OnLoad(EventArgs e)
{
Literal lit = new Literal();
lit.Text = "<span ID=\"Literal1\" runat=\"server\">test</span><input id=\"Button1\" type=\"button\" value=\"button\" onclick=\"UpdateTime();\" />";
this.Controls.Add(lit);
}
protected override void Render(HtmlTextWriter writer)
{
if (!this.DesignMode)
sm.RegisterScriptDescriptors(this);
base.Render(writer);
}
[WebMethod]
public static string GetCurrentDate()
{
return DateTime.Now.ToString();
}
#region IScriptControl Members
IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
{
return null;
}
IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
{
ScriptReference reference = new ScriptReference();
reference.Path = ResolveClientUrl("~/tests/JScript.js");
return new ScriptReference[] { reference };
}
#endregion
}
}
Now, in my sample page, when I click the button, I get this error:
PageMethods is not defined
[Break on this error] PageMethods.GetCurrentDate(OnSucceeded, OnFailed);
How do I call GetCurrentDate from the clientscript that my control registers?
There is actually no fully encapsulated method for implementing AJAX callbacks against methods of a server control yet, as of v3.5. It's a very frustrating limitation.
The most common solution is to create an HttpHandler in your server control's assembly, then require that the handler be registered in the web.config. Look at how ASP.NET AJAX's ScriptResource.axd is wired up in the web.config in ASP.NET AJAX 1.0, for example.

Resources