Access isvalid property of ASP.NET validators in Javascript - asp.net

I have read here that any ASP.NET validator has a property called: isvalid. This property can be used in client side to check if the validator successfully passed the validation or not.
I tried to access this property as following but for some reason the code fail:
alert(document.getElementById("validator_clientID").isvalid);
Do you have any idea why this is not working?

I found same !
try this document.getElementById('XXX').Validators[0].isvalid It's working for me

I don't think the isvalid works on a validator control directly as this is a server side validation function. You can fire a validator check for the current page or validation group using the client side javascript function Page_ClientValidate. You can optionally specify a validation group name a parameter. This will return true if all the validation passes.
You can also look at more available client-side functions and how they map to the server side functions on MSDN at:
http://msdn.microsoft.com/en-us/library/yb52a4x0.aspx

Kindly have a look at the solution below that iterates through all validators and display validators which are invalid at the client side
var varray=new Array();
for (var i = 0; i < Page_Validators.length; i++)
{
if(!Page_Validators[i].isvalid)
{
varray.push(Page_Validators[i])
}
}
varray;
You can paste this code in console to get invalid validators

Remember to call
IsValid
instead
isvalid
(may vary)

On client side Javascript:
var controlIsValid = this.document.getElementById("validatorID").attributes.isvalid.value;

Related

webservice returning 500 asp.net

Got a very weird problem.
I just successfully implemented a simple ajax validation on my site (Yey!). I hooked up the validation to the OnFocusOut event of every textbox via backcode, which runs perfectly.
The weird bug happens when,on the same page , I call the exact same method and pass the same parameters via a validate() method or add the attribute OnFocusOut on document.ready() . I keep getting a status of 500.
I was able to verify that the server side method isn't successfully called when using validate() but runs when OnFocusOut is triggered.
WebServiceAdapter
function ValueChanged(target, validationDiv,valueType) {
targetControl = document.getElementById(validationDiv);
// Added this part because I'm guessting a null is causing it
var str = (target.value === '') ? " " : target.value;
switch (valueType) {
case "email":
webServiceAdapter.EmailExist(str);
break;
case "screenName":
webServiceAdapter.ValidScreenName(str);
break;
case "changePassword":
webServiceAdapter.PasswordCorrect(str);
break;
}
Adding OnFocusOut backcode - WORKS
txtEmail.Attributes.Add("onfocusout", "ValueChanged(this,'"+Email.ClientID+"','email')");
Adding OnFocusOut jquery - DOES NOT WORK
$("#<%=txtEmail.ClientID%>").attr("onfocusout", "ValueChanged('<%=txtEmail.ClientID%>', '<%=Email.ClientID%>', 'email')");
Calling via validate() method - DOES NOT WORK
ValueChanged('<%=txtEmail.ClientID%>', '<%=Email.ClientID%>', 'email');
Edit:
I'm also getting this error "An error occurred: Invalid web service call, missing value for parameter: 'email'." After invoking validate()
Solved the problem.
Quite embarrassing really. It was a "common sense bug".
ValueChanged() was expecting an object as the first parameter - this is what the backcode is doing by using "this". For the call from validate(), i was using the ID.

Prevent value to be preserved in ModelState

Good day!
ASP.NET MVC makes a good job by storing values of inputs during GET/POST cycle inside ModelState and automagically putting them into inputs in case of validation errors.
But on my form I have CAPTCHA field which shouldn't be preserved during validation errors (CAPTCHA value is regenerated on each request).
I've tried to achieve this by setting
if (TryUpdateModel(model))
{
// ...
}
else
{
ModelState.Remove("CaptchaValue"); // ModelState does have CaptchaValue
return View(model); // CaptchaValue is empty in model
}
But it doesn't work.
May be there is an attribute which I can apply to my model field to prevent it from preserve in ModelState?
Thanks in advance!
You can use the bind attribute on the action parameter to control model binding behaviour:
public ActionResult YourActionName([Bind(Exclude = "CaptchaValue")]ModelType model)
I've found this in nearby thread MVC - How to change the value of a textbox in a post?:
ModelState.SetModelValue("CaptchaValue", new ValueProviderResult(String.Empty, String.Empty, System.Threading.Thread.CurrentThread.CurrentCulture));
But it seems to be a bit ugly.

How to pass an additional parameter to CascadingDropDown ServiceMethod?

I have two chained CascadingDropDowns. Both are working fine.
The thing is that in the underlying web methods which are supplying values for DropDwonList I need read one additional parameter. This parameter is needed for setting up the default item for dropdownlist.
I do not know how to pass that parameter or read it.
I've read on the Internet about the ContextKey property. But I do not know how to acces it from the WebMethod.
I've tried to get to the session through HttpContext.Current.Session (hoping that I could extract some parameter from the session) but it seams that the Session is different for the WebPage and WebMethod.
So I am lost here, any ideas?
You need three things to get the ContextKey to work.
Set UseContextKey property on the CascadingDropDown to true
Change the method signature of your webmethod to accept the contextKey parameter:
public CascadingDropDownNameValue[] GetDropDownContents(
string knownCategoryValues, string category, string contextKey) { ... }
NOTE: The parameter has to be exact casing.
Set the ContextKey using JavaScript. The AJAX CascadingDropDown exposes getter/setter for this property in the DOM:
document.getElementById('idOfCDDL').set_contextKey('valueyouwant');
HTH.
Passing Additional arguments
Sometimes the action method which provides the JSON for the combobox may need additional arguments. Here is how to pass them to your action:
CopyPassing additional arguments to the action method
function onComboBoxDataBinding(e) {
e.data = $.extend({}, e.data, { customParam: "customValue"});
}
In your .cs file write:
cascadingdropdown1.contextKey=<parameter you need>
Then in the web method use that contextKey

Calling Javascript After Web Method has fired

I'm trying to implement the cascading dropdown from the toolkit. I need to get the count in a sub category dropdown, if it's zero then I turn off the visibility of the sub category.
If I use the javascript OnChange event then my script fires before the web method, so I need to know how to fire my script AFTER the web method has fired please.
My demo page: http://bit.ly/92RYvq
Below is my code and the order I need it to fire.
[WebMethod]
public CascadingDropDownNameValue[] GetSubCats1(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
int CategoryID;
if (!kv.ContainsKey("Category") || !Int32.TryParse(kv["Category"], out CategoryID))
{
return null;
}
dsSubCat1TableAdapters.Categories_Sub1TableAdapter SubCats1Adapter = new dsSubCat1TableAdapters.Categories_Sub1TableAdapter();
dsSubCat1.Categories_Sub1DataTable SubCats1 = SubCats1Adapter.GetSubCats1(CategoryID);
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
foreach (DataRow dr in SubCats1)
{
values.Add(new CascadingDropDownNameValue((string)dr["SubCategory1"], dr["SubCatID1"].ToString()));
}
return values.ToArray();
}
function getSubCatCount() {
$get("ddlSubCats1").style.display = $get("ddlSubCats1").length > 1 ? "block" : "none";
}
Generally when you call your web method function through javascript you can supply it two call back functions. One gets fired if there is an error and the other gets fire once the web method call has been completed. The callback requires two arguments, the result and a context. For example if your function was called myWebMethodFunction and your namespace it was contained in was my.fully.qualified.namespace it may look like this.
my.fully.qualified.namespace.myWebMethodFunction(param1, param2, ... , paramN, onErrorCallback, onCompleteCallback, context);
Once that function finishes, it will call the onCompleteCallback passing the result of your webmethod function and whatever you passed for a context.
It has been a while since I've called a web method function so I might have gotten the order of the callback reversed.
For some reason I can't comment on things either, but I can add to this.
I may be thinking about something different, but you must be calling something through javascript to fire your webmethod, correct? Whatever you use to call the webmethod through javascript should provide a mechanism to add a callback that will be fired once your webmethod call is complete and returned.
Use jQuery.ajax() it allows you to specify a success function and a failure function that fire after the web method returns.

Asp.net MVC User Control ViewData

When a controller renders a view based on a model you can get the properties from the ViewData collection using the indexer (ie. ViewData["Property"]). However, I have a shared user control that I tried to call using the following:
return View("Message", new { DisplayMessage = "This is a test" });
and on my Message control I had this:
<%= ViewData["DisplayMessage"] %>
I would think this would render the DisplayMessage correctly, however, null is being returned. After a heavy dose of tinkering around, I finally created a "MessageData" class in order to strongly type my user control:
public class MessageControl : ViewUserControl<MessageData>
and now this call works:
return View("Message", new MessageData() { DisplayMessage = "This is a test" });
and can be displayed like this:
<%= ViewData.Model.DisplayMessage %>
Why wouldn't the DisplayMessage property be added to the ViewData (ie. ViewData["DisplayMessage"]) collection without strong typing the user control? Is this by design? Wouldn't it make sense that ViewData would contain a key for "DisplayMessage"?
The method
ViewData.Eval("DisplayMessage")
should work for you.
Of course after I create this question I immediately find the answer after a few more searches on Google
http://forums.asp.net/t/1197059.aspx
Apparently this happens because of the wrapper class. Even so, it seems like any property passed should get added to the ViewData collection by default.
I really need to stop answering my own questions :(

Resources