Soe Tun

my attempt to solve common tech problems

  Home  |   Contact  |   Syndication    |   Login
  14 Posts | 0 Stories | 211 Comments | 0 Trackbacks

News

Twitter







Archives

Post Categories

Image Galleries

UPDATE (2011-01-28):  ASP.NET MVC 3

I have a newer blog post that shows how to get Client Side Validation Summary without doing any of this.
I will still be answering questions and supporting this for developers who are still using ASP.NET MVC 2.

If you are on ASP.NET MVC 3, go here.

 

Problem

The MicrosoftMvcJQueryValidation.js script file, which integrates with the jQuery Validation Plugin, does NOT populate validation errors inside the Validation Summary control.
I will show you how to populate validation error messages into the Validation Summary control <%= Html.ValidationSummary("Please fix the following errors.") %>.

This code works 100% for both ASP.NET MVC 2 (Release Candidate 2) and ASP.NET MVC 2 RTM.
Sample Project download link at the bottom of the blog post.
 

Goal

We are going to tweak it to do the following.

  1. Inserts the client-side error messages into the Validation Summary <%= Html.ValidationSummary("Please fix the following errors.") %>  control.
  2. Show only asterisks for the  <%= Html.ValidationMessage("ColumnName")%> controls.

 

 Additionally, I am going to use only THREE JavaScript files because I don't want to use the other Validation JavaScript Library that comes with the MVC 2.0.

<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js"></script>
<script type="text/javascript" src="<%= Url.Content("~/scripts/MicrosoftMvcJQueryValidation.js") %>"></script>

Yes, Microsoft CDN supports SSL, and that is why you are seeing https above.

 

Missing MicrosoftMvcJQueryValidation.js File

ASP.NET MVC 2 (Release Candidate 2) does NOT come with the MicrosoftMvcJQueryValidation.js script file like the ASP.NET MVC 2 (Beta) version.
So download the MVC RC2 source code from the CodePlex ASP.NET MVC section.
The MicrosoftMvcJQueryValidation.js script file is included in there somewhere.

 

Step 1: Create My Own Html Extension Method for Validation Summary

I need to use the following jQuery Validation Plugin's options to insert client-side validation error messages into my Validation Summary DOM node.

  1. errorContainer      === hide and show this container when validating.
  2. errorLabelContainer === hide and show this container when validating.
  3. wrapper             === wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages.

 

Problem is that  <%= Html.ValidationSummary("Please fix the following errors.") %>  control does NOT render when there are no ModelState errors.
Only when there are ModelState errors, it renders out like this.

<div class="validation-summary-errors">
	<span>Please fix the following errors.</span>
	<ul>
		<li>Error Message</li>
	</ul>
</div>

 

Because of that behavior, it presents a  slight problem with how we are going to integrate with the jQuery Validation Plugin.
So, we are going to create an Extension Method for the HtmlHelper class to render the HTML code at all times.

public static MvcHtmlString ValidationSummaryJQuery(this HtmlHelper htmlHelper, string message, IDictionary<string, object> htmlAttributes)
{
	if (!htmlHelper.ViewData.ModelState.IsValid)
		return htmlHelper.ValidationSummary(message, htmlAttributes);


	StringBuilder sb = new StringBuilder(Environment.NewLine);

	var divBuilder = new TagBuilder("div");
	divBuilder.MergeAttributes<string, object>(htmlAttributes);
	divBuilder.AddCssClass(HtmlHelper.ValidationSummaryValidCssClassName); // intentionally add VALID css class

	if (!string.IsNullOrEmpty(message))
	{
		//--------------------------------------------------------------------------------
		// Build an EMPTY error summary message <span> tag
		//--------------------------------------------------------------------------------
		var spanBuilder = new TagBuilder("span");
		spanBuilder.SetInnerText(message);
		sb.Append(spanBuilder.ToString(TagRenderMode.Normal)).Append(Environment.NewLine);
	}

	divBuilder.InnerHtml = sb.ToString();
	return MvcHtmlString.Create(divBuilder.ToString(TagRenderMode.Normal));
}

 

 

Step 2: Changes to Your MVC Views

Replace all of your
<%= Html.ValidationSummary("Please fix the following errors.") %>
with
<%= Html.ValidationSummaryJQuery(
       
"Please fix the following errors.",
        new Dictionary<string, object> { { "id", "valSumContainer" /* This is important. You can change the "id" attribute value, but don't remove it */ } }) %>

 

Replace all of your
<%= Html.ValidationMessageFor(m => m.ColumnName)%>  with  <%= Html.ValidationMessageFor(m => m.ColumnName, "*") %>.
<%= Html.ValidationMessage("ColumnName")%>          with  <%= Html.ValidationMessage("ColumnName", "*") %>.

The reason is that I want to display a little asterisk next to the User Input Fields, and actual error message inside the Validation Summary.

 

Make sure your HTML Form Declaration Looks like this

<% Html.EnableClientValidation(); // IMPORTANT: this line MUST be *before* Html.BeginForm() block %>
<% using (Html.BeginForm()) { %>

	<!-- IMPORTANT: ViewContext.FormContext.ValidationSummaryId MUST match the Validation Summary ID defined inside Html.ValidationSummaryJQuery() block */ -->
	<% ViewContext.FormContext.ValidationSummaryId = "valSumContainer"; %>

<% } %>

Use these CSS styles and you can tweak them if you'd like to.

/*----------------------------------------------------------
ASP.NET MVC FRAMEWORK DEFAULT CSS CLASS NAMES
----------------------------------------------------------*/
.error,.field-validation-error{color:red}

.input-validation-valid,.field-validation-valid,.validation-summary-valid{display:none}
.input-validation-error{background-color:#fee;border:1px solid red; outline: none}
.input-validation-error:focus{outline:none}
input[type="text"].input-validation-error:focus, select.input-validation-error:focus{outline:none}

.validation-summary-errors{color:red}
.validation-summary-errors span{font-weight:700}
.validation-summary-errors ul{list-style:disc inside}
.validation-summary-errors ul li{font-weight:normal}
.validation-summary-errors ul li label, .validation-summary-errors ul li span{display:inline !important; font-weight:normal}

 

 

Step 3: Custom Code for the MicrosoftMvcJQueryValidation.js File

Let's add the following code into the MicrosoftMvcJQueryValidation.js script file.

var validationSummaryId = validationContext.ValidationSummaryId;
if (validationSummaryId) {
	// insert an empty <ul> into the validation summary <div> tag (as necessary)
	$("<ul />").appendTo($("#" + validationSummaryId + ":not(:has(ul:first))"));

	options = {
		errorContainer: "#" + validationSummaryId,
		errorLabelContainer: "#" + validationSummaryId + " ul:first",
		wrapper: "li",

		showErrors: function(errorMap, errorList) {
			var errContainer = $(this.settings.errorContainer);
			var errLabelContainer = $("ul:first", errContainer);

			// Add error CSS class to user-input controls with errors
			for (var i = 0; this.errorList[i]; i++) {
				var element = this.errorList[i].element;
				var messageSpan = $(fieldToMessageMappings[element.name]);
				var msgSpanHtml = messageSpan.html();
				if (!msgSpanHtml || msgSpanHtml.length == 0) {
					// Don't override the existing Validation Message.
					// Only if it is empty, set it to an asterisk.
					messageSpan.html("*");
				}
				messageSpan.removeClass("field-validation-valid").addClass("field-validation-error");
				$("#" + element.id).addClass("input-validation-error");
			}
			for (var i = 0; this.successList[i]; i++) {
				// Remove error CSS class from user-input controls with zero validation errors
				var element = this.successList[i];
				var messageSpan = fieldToMessageMappings[element.name];
				$(messageSpan).addClass("field-validation-valid").removeClass("field-validation-error");
				$("#" + element.id).removeClass("input-validation-error");
			}

			if (this.numberOfInvalids() > 0) {
				errContainer.removeClass("validation-summary-valid").addClass("validation-summary-errors");
			}

			this.defaultShowErrors();

			// when server-side errors still exist in the Validation Summary, don't hide it
			var totalErrorCount = errLabelContainer.children("li:not(:has(label))").length + this.numberOfInvalids();
			if (totalErrorCount > 0) {
				$(this.settings.errorContainer).css("display", "block").addClass("validation-summary-errors").removeClass("validation-summary-valid");
				$(this.settings.errorLabelContainer).css("display", "block");
			}
		},
		messages: errorMessagesObj,
		rules: rulesObj
	};
}

 

A Few Important Things

  1. Properties like this.errorList and this.successList in my code above are NOT documented properties of the jQuery Validation Plugin.
    I used FireBug AddOn (everybody loves it, who doesn't) in FireFox to step into the JavaScript debugging and inspected the properties available in the jQuery validation plugin "class".

    Therefore, if the jQuery Validation Plugin author(s) change(s) any of these property names in the future, this code will NOT work.
    The jQuery Validation Plugin Version I am currently using is jQuery Validation Plugin (Version 1.6).

     
  2. I have tested my code works correctly on IE6-IE7-IE8, FireFox, and Google Chrome browsers.
    I don't know if it works in Opera or other browsers. You're on your own for that.

     
  3.  
  4. Currently, there is ONE known-issue I have not resolved with my code yet.
    If you have Server-Side Error Messages in your Validation Summary and zero Client-Side Error Messages, and you click on one of the User Input Fields (textboxes, dropdowns), the Validation Summary will disappear.

    This happens because the jQuery Validation Plugin thinks there are no errors since my code above cannot count the Server-Side errors populated in the Validation Summary.
    I know how to do that already, but I am just a bit lazy at the moment.

    If you are interested in implementing it yourself, I will give you a hint.

    The client-side error message <li> tags generated by the jQuery Validation Plugin contains the <label for="inputFieldID"> tags.
    example:   <li><label generated="true" for="inputFieldID">Error Message</label></li>

    But the server-side error messages do not contain the <label for="inputFieldID"> tag.
    example:   <li>Error Message</li>

 

 

Step 4: Where to Add the Step #3 Custom Code in the MicrosoftMvcJQueryValidation.js File

We are not replacing any existing code in the MicrosoftMvcJQueryValidation.js script file.

We are only ADDING my custom code block near the bottom of it where it defines the JavaScript Variable (jQuery Validation Plugin Options)   var options = { ... }.
So add my code block right after the  var options = { ... }  original block.

 

The reason is that I want to keep the default client-side validation behavior, and only use my behavior if and only if the Validation Summary Container ID is specified.
That is why I said the "id" attr is important when I wrote this code.

<%= Html.ValidationSummaryJQuery(
       
"Please fix the following errors.",
        new Dictionary<string, object> { { "id", "valSumContainer" /* This is important. You can change the "id" attribute value, but don't remove it */ } }) %>

 

I hope this is very useful to some people who are obsessive compulsive like me that wants to keep JavaScript Library <script> includes to a minimum.

Cheers,
Soe
 

Here is the sample project download link

 

Change History

==== March 3rd 2010 ==== 
Updated the code so that it does not hide the Server-Side errors anymore.

==== March 22nd 2010 ====
BUGFIX:   for update for Showing/Hiding Server-Side errors.

==== April 5th 2010 ====

(1) Changed the Html.ValidationSummaryJQuery( ) extension method to **not** insert an empty UL tag.
      Because, empty <UL> tag without any child <LI> tag is not XHTML-compliant.
      Instead, insert an empty <UL> tag from the client-side JavaScript.

(2) If the Validation Message <span> has its own message text, do not override it with an asterisk '*' and keep the default.
      If and only ifthe validation message <span> is empty, set its innerHTML to an asterisk.
      This change was implemented based on Naz's comment below but a bit different from his implementation. 

posted on Saturday, February 27, 2010 1:33 PM

Feedback

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 3/21/2010 1:28 AM Kevin JEnsen
This is absolutely fantastic. Soe, Can you link a downloadable sample application?



# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 3/22/2010 6:22 PM Soe Tun
Hi Kevin,

please try downloading the sample project from my Windows Live SkyDrive link.
Let me know if it doesn't work.

Thanks,
Soe

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 3/22/2010 9:31 PM Jim Geurts
Awesome, exactly what I was looking for! Thanks!

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 4/3/2010 6:17 AM pelle
Awesome, thanks!

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 4/4/2010 5:36 PM Naz
Hey thanks for the code i've modified it slightly to allow for it work with the existing validation messages or any custom inline messages taken from ValidationMessageFor eg. *

Simply replace

// set inner HTML of Error Message <span> to an asterisk because it is empty by default at start
$(messageSpan).removeClass("field-validation-valid").addClass("field-validation-error").html(validationMessage);

with
// Overwrite messages with inline messages if available
var validationMessage = $(messageSpan).html();
if (validationMessage.length == 0)
validationMessage = errorList[i].message;

$(messageSpan).removeClass("field-validation-valid").addClass("field-validation-error").html(validationMessage);

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 4/6/2010 5:59 PM Giovanni Bassi
Thanks, man! You spared us several hours.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 4/14/2010 1:28 AM Raj Aththanayake
Fantastic. Just what I'm looking for..

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 7/13/2010 3:44 AM Nour
fantastic!
but i have a problem using it.
sometimes it looks that the code doesn't work correctly,
for example, if the field 'Name' is required and you didn't fill it, however there is no error message
until you go to the next field and make a mistake there, then the two fields are validated.
i can't figure out how this happen!?
BTW
i'm using these links

<script type="text/javascript" src="../../Scripts/jquery-1.4.2.js"></script>
<script type="text/javascript" src="../../Scripts/jquery-ui.min.js"></script>
<script type="text/javascript" src="../../Scripts/jQuery.Validate.js"></script>
<script type="text/javascript" src="../../Scripts/MicrosoftMvcJQueryValidation.js"></script>


# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 7/31/2010 7:03 AM Jurgo
How to do validation groups(like in asp,.net) using Html.ValidationSummary.
If i dont need to display all validation errors in one place. Is there any way to split Html.ValidationSummary output?

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 7/31/2010 5:19 PM Soe Tun
@Jurgo

it is just a matter of having 2 or more <form> tags and their own Validation Summary declaration.

However, it is not possible to have multiple Validation Groups within the same form.
Let me know if you still have questions.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 9/20/2010 7:46 AM Satya Srikant Mantha
Dear Soe,

Its a wonderful fix you provided, working for normal forms. However I am trying this fix in a Modal Dialog containing a form. I want the validation errors to be displayed in the Same Dialog. Can you please guide me how to achieve this ?

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 9/20/2010 12:16 PM Soe Tun
@Satya It is the same concept.

Just include these in the DIV tag that you use for Modal Dialog.
(1) a validation summary declaration
(2) Html.BeginForm() with reference to the Val. Sum from #1


Your validation summary and FORM tag should be inside the Modal Dialog window to be displayed in the Modal Dialog.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 9/21/2010 1:35 AM Satya Srikant Mantha
Hi Soe,

This is the code I am using :



<script type="text/javascript">
$("#OkCreate").live('click', function() {
$("#ExpenseLineForm").validate();
if ($("#ExpenseLineForm").valid()) {
$.post("ExpenseClaim/UpdateExpenseLine", $("#ExpenseLineForm").serialize(),
function(htmlResult) {
$("#ExpenseSheet").html(htmlResult);
});
$("#ExpenseLineEditModal").dialog('close');
}
else { return false; }
});

</script>
<div id="ExpenseLineEditModal">
<% Html.EnableClientValidation(); %>
<%= Html.ValidationSummaryJQuery("Please fix these errors.", new Dictionary<string, object> { { "id", "valSumIdLineCreate" } })%>

<% using (Ajax.BeginForm("UpdateExpenseLine", "ExpenseClaim", new AjaxOptions { UpdateTargetId = "ExpenseSheet", HttpMethod = "Post" }, new { id = "ExpenseLineForm" }))
{ %>
<% ViewContext.FormContext.ValidationSummaryId = "valSumIdLineCreate"; %>
<% ViewContext.FormContext.ReplaceValidationSummary = true; %>
<% Html.RenderPartial("ExpenseLineModelEditor", Model); %>
<p align="right">
<button id="CancelCreate" name="Cancel" type="submit">
Cancel</button>
<button id="OkCreate" name="Ok" type="submit">
Ok</button></p>
<% } %>
</div>

The Dialog is an Ajax.Form and i am explictly posting it by clicking on Ok button which has a jquery event handler associated with it.

Can you please guide me where I am wrong.


# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 9/21/2010 11:44 AM Soe Tun
@Satya

You are probably having a problem because you have 2 different Event Handlers attached to your [Ok] button.
(1) Ajax.BeginForm() declaration attaches event handler to submit using Microsoft AJAX
(2) And your $("#OkCreate").live('click') attaches another event handler.


Just simply change your Ajax.BeginForm() to Html.BeginForm() and try again because you are already validating in your $("#OkCreate").live('click') code.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 9/24/2010 3:05 AM Tobias
Great script,
I only have one problem: my <%=Html.ValidationMessageFor(model => model.Name, "*") %> is only showing "*", but in my Validationsummary shows the correct Errormessage provided in my DataAnnotations class.


# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 9/24/2010 5:50 AM Tobias
And my dataannotations entity look like this:
[DisplayName("Name")]
[Required(ErrorMessage = "{0} is required")]
public string Name{ get; set; }

Please help. If I use the other validation "MicrosoftMvcValidation.js" it works.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 10/11/2010 9:33 AM Alberto
Great article, Soe.

I am having problems when I use a custom for name.
I've asked for help here:
http://stackoverflow.com/questions/3906667/enableclientvalidation-with-multiple-forms
Maybe you know how to fix this.
Thanks for your help

Alberto

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 10/12/2010 1:26 AM Soe Tun
Hi Alberto,

I guess you figured out why it isn't working for you.
Yes as you noticed, my HTML Helper Extension method accepts a Dictionary.


I didn't like using the `object` and converting it to a `Dictionary` using Reflection.
That's why I intentionally was using the `Dictionary`.

Sorry I replied late, but I'm glad you figured it out.
Maybe I'll add in a new extension method that accepts an `object`.

-Soe

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 10/28/2010 5:30 PM Marko
HI, i have problem with extension part of this plugin
HtmpHelper class doesn't recognise ValidationSummaryJQuery as a extension so i have the folowing error:
'' 'System.Web.Mvc.HtmlHelper<G2G.Web.ViewData.G2GMessagesViewData>' does not contain a definition for 'ValidationSummaryJQuery' and no extension method 'ValidationSummaryJQuery' accepting a first argument of type 'System.Web.Mvc.HtmlHelper<G2G.Web.ViewData.G2GMessagesViewData>' could be found (are you missing a using directive or an assembly reference?)

"

Please Help,
Thanks

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 10/28/2010 6:03 PM Soe Tun
Hi Marko,

when you added the HTML Helper Extension class to your project,
it could have been added with a default NAMESPACE of your project.


You have two options.
(1) Make that HTML Helper Extension without a namespace.
(2) Add the corresponding namespace reference to your Web.config file
under <pages> <namespaces> element.
In your case, it will be something along the line

<pages>
<namespaces>
<add name="G2G.Web" /> <!-- namespace of your HTML Helper Extension class -->
</namespaces>
</pages>


Let me know if it still doesn't work.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 10/29/2010 10:58 AM Marko
Hi Soe,
it helps me. Everything works fine

thanks a lot

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 11/3/2010 9:58 AM Harry
Hi Soe,

This is great, it is just what I was looking for!

I implemented it in my solution and it is working except that my errors do not get wrapped in "label for" and as such do not link to their respective inputs.

Any ideas on where I should be looking to fix this?

Thanks!

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 11/4/2010 12:26 PM Soe Tun
Hi Harry,

the Error Messages in the Validation Summary should be wrapped in a <label> tag.
Try clicking on them and it'll switch focus into a corresponding UI control.


I am not sure about the '*' asterisk symbols displayed next to the UI control tho.
For that, you'll have to see if it gets rendered as a <label> using FireBug.

Let me know if you have any more question.

Soe

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 1/6/2011 1:45 AM jonh
Hi All,
I am using mvc 3 unobtrusive concept for validation . It is working fine at client/server side.The problem is that it wont clear after server side code is get excecuted.

Is there any extra code i have to write to clear validation summary ?

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 1/7/2011 6:18 PM Soe Tun
@John

I haven't gotten a chance to play with MVC3 yet.
I'll look into it this weekend and see if it is my code that needs to be updated.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 1/9/2011 5:45 PM mare
Hey, this solution seems to work fine for simple cases but when I have a model that I render via EditorFor() helper this code fails, specifically the JS in MicrosoftMvcJQueryValidation.js throws out errors. Probably it has something to do with the EditorFor() helper changing the IDs on the fly?

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 1/27/2011 10:44 AM Andreas
It seems like even if I have a validation message set, it will always be overridden by an asterix. messageSpan is null since fieldToMessageMappings also is null.
Any ideas what could be wrong? The problem occurs on pages where I don't want to use this helper and just output the message next to the elements. Now it justs output *.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 1/27/2011 10:46 PM Soe Tun
@Andres I'm looking into it right now. I'll give an update soon.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 1/27/2011 10:59 PM Soe Tun
@Andres

You must remove the line that assigns a value to the following inside your view.
This one below...remove it and it should be working as it is.

<% ViewContext.FormContext.ValidationSummaryId = "valSumId"; %>


I am currently working on releasing a new version for the ASP.NET MVC 3.
So expect some changes soon.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 1/28/2011 3:43 AM Soe Tun
@Andres

Please change
<%= Html.ValidationMessageFor(model => model.LastName, "*") %>
to
<%= Html.ValidationMessageFor(model => model.LastName) %>


Because the "*" parameter for ValidationMessageFor() method overrides your Error Message defined with Validation Metadata Attribute.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 2/19/2011 6:52 AM Prateek Sasanker
Soe,
Da comcept is fantastic......However i am having a problem. Actually I have four solutions in my project.
The solution which holds my views are using code inherited from another solution. So, when I am using
<%= Html.ValidationSummaryJQuery("Please correct the errors and try again.", new Dictionary<string, object> { { "id", "valSumId" } } )%>
in my view its giving an error "System.Web.Mvc.HtmlHelper<AnotherSolution>" does not contain a definition for "ValidationSummaryJQuery" and no extension method "ValidationSummaryJQuery" accepting a first argument of type "System.Web.Mvc.HtmlHelper<AnotherSolution>" could be found (are you missing a using directive or an assembly reference?)

CAN YOU/ANYONE CAN HELP ME???

Thanks,
Prateek.

P.S. Its Urgent.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 2/19/2011 4:43 PM Soe Tun
Hi Prateek,

if you look through the questions posted in this blog post, you can already find the answer for your problem.

http://geekswithblogs.net/stun/archive/2010/02/27/asp.net-mvc-client-side-validation-summary-with-jquery-validation-plugin.aspx#545013

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 2/21/2011 1:25 AM Prateek Sasanker
Thanks Soe.
It worked fine!!!!


Regards,
Prateek.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 2/21/2011 2:47 AM Prateek Sasanekr
Soe, I am Having one other problem. Thought you can help me figure it out.
There are four solutions in my project. All my controllers and Views are declared in the Presentation solution. There are auto-generated class files in the solution named DomainModel. So, my views inherits these auto-generated files from the DomainModel solution. The problem is that I can't modify these auto-generated files by using Data Annotations in there. Hence, cannot accomplish my validation. I tried by creating partial classes but no result. By creating a class file in my Presentation solution and then binding it with the view the validation works fine. But my views are binded with the class files (auto-generated) from the DomainModel.

Can you help me work it out so, that validation works with those classes without modifying it.

Thanks,
Prateek.

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 4/21/2011 4:40 AM Malte
Has anyone got this to work with partial (.ascx) views? I can see the labels being generated, so the validation is taking place (and preventing the post) - but they're being inserted straight after the input elements instead of being added to the validation summary container.

I've got:
<%= Html.ValidationSummaryJQuery("Oops!", new Dictionary<string, object>
{ { "id", "createFavouriteValidationSummaryContainer" }, {"class", "validationSummaryContainer" } }) %>
<% Html.EnableClientValidation(); %>
<% using (Html.BeginForm("CreateFavourite", "TodoItem", FormMethod.Post, new { id = "FSP_Create_Form" })) %>
<% { %>

I've tried the suggestions here: http://stackoverflow.com/questions/2652586/asp-net-mvc-2-loading-partial-view-using-jquery-no-client-side-validation

Still no luck though - help! :)

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 4/21/2011 9:22 AM Malte
Duh - completely missed the $(document).ready at the bottom of MicrosoftMvcJQueryValidation.js

Finally stumbled upon the answer here: http://awesome.codeplex.com/discussions/238661

You can modify your MicrosoftMvcJQueryValidation.js at the end to look like this:

// need to wait for the document to signal that it is ready
$(document).ready(enableClientValidation());

function enableClientValidation() {
var allFormOptions = window.mvcClientValidationMetadata;
if (allFormOptions) {
while (allFormOptions.length > 0) {
var thisFormOptions = allFormOptions.pop();
__MVC_EnableClientValidation(thisFormOptions);
}
}
}

Which will allow you to to add a simple call at the bottom of your partial view to solve this problem:

<script type="text/javascript">
enableClientValidation();
</script>

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 5/19/2011 2:52 PM Cedd-Dev
Hi,

Actually that's really working fine for me but I amended the solution in order to avoid having to put his line each time in the view :

<% ViewContext.FormContext.ValidationSummaryId = "valSumContainer"; %>

In order to accomplish this, I simply added these few line of codes in the Helper Extencsion ValidationSummaryJquery :

string FormValidationSummaryId;
object oFormValidationSummaryId;

try
{
htmlAttributes.TryGetValue("id", out oFormValidationSummaryId);
FormValidationSummaryId = oFormValidationSummaryId.ToString();

if (htmlHelper.ViewContext.FormContext != null && FormValidationSummaryId.Length > 0)
{
htmlHelper.ViewContext.FormContext.ValidationSummaryId = FormValidationSummaryId;
}
}
catch
{
//do nothing
}


I know it's some more work, but it happens only 1 time thus saving time & error typing when it comes to deal with sites with several forms.

My little 2 cents for an almost deprecated framework,

Ced

# re: ASP.NET MVC Client-Side Validation Summary with jQuery Validation Plugin 11/5/2011 8:49 PM Pablo
Hi SoeLinn: Nice blog and good article, I was dealing with something like this, I had a project that was started on MVC2, I am trying to add a smoothpopup with a create/edit form, but I have a problem with the validation summary, can you take a look on the post I leave on the asp.net forum, may be you can help me or give me some clue on how to solve this.
http://forums.asp.net/t/1736434.aspx/1?MVC2+Jquery+Create+a+smooth+popup+with+a+form+that+include+validation
Thanks in advance.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: