I have a web page that has a few text boxes, and a dual list control. All of these data elements are for a particular entity. The form is for creating a new instance of this entity and saving it to the database. The dual list shows available people to use, and the user can move options from the available list to the selected list. All of this works perfectly when posted. There is a button at the bottom of the page to post the form.
To make things easy, I also want to include a hidden "form" that lets the user add a new person to the dual l开发者_如何转开发ist without leaving the page. They click an "Add New" link which shows a previously hidden div. In the div are two text boxes: "emailName" and "emailAddress", and a button to click called "Add".
When the user clicks the "Add" button I need to validate the emailName and emailAddress fields, and only those two fields. If they are valid then I will make my AJAX request and handle the return data by adding a new option to the dual list.
Here's the solution I am using.
First, I disable validation of my partial's form elements and never re-enable it. I do this by specifying a class selector in the validator options using a custom script that's referenced in the main page.
Then, on my parital's button click I call validator.element for each element. If they are all valid then I perform the AJAX request.
Calling .element will show the validation message for the field and return a boolean indicating if it's valid. You have to check these carefully to avoid boolean operator short-circuiting issues, to make sure all the error messages get shown. I used the bitwise & to accomplish this.
var validator = $("#EmailRecipient_Name").closest("form").validate();
//validator.settings.defaultIgnoreClass is defined in a custom script, and set to ".ignoreValidation"
$("#EmailRecipient_Name").addClass(validator.settings.defaultIgnoreClass);
$("#EmailRecipient_Email").addClass(validator.settings.defaultIgnoreClass);
$("#addNewRecipientLink").click(
function () {
$("#addNewRecipientBox").toggle()
return false;
}
);
$("#addNewRecipient").click(
function(){
var validator = $("#EmailRecipient_Name").closest("form").validate();
if ( validator.element( "#EmailRecipient_Name" ) & validator.element( "#EmailRecipient_Email" ) )
{
$.post(
"@Url.Action( "Create", "EmailRecipient" )",
{
Name: $("#EmailRecipient_Name").val(),
Email : $("#EmailRecipient_Email").val()
},
function( data ){
if ( data.ErrorMessage )
{
alert( data.ErrorMessage );
}
else
{
$("#SelectedEmailRecipients").append("<option value='" + data.EmailRecipientID + "'>" + data.Name + "</option>");
$("#EmailRecipient_Name").val("");
$("#EmailRecipient_Email").val("");
}
}
);
}
return false;
}
);
精彩评论