5

This is my Model property

 public ModelStateDictionary modelSateClientSide { get; set; }

Now I called the Property in JavaScript and add the error in my ModelState

if (parseInt(academicAchievement, 10) > parseInt(peAcademicAchievement, 10))
{
 @Model.modelSateClientSide.AddModelError(string.Empty, "xxx");
 return false;
}

Am I doing it correctly? And I got a error in above line:

The best overloaded method match for System.Web.WebPages.WebPageExecutingBase.Write(System.Web.WebPages.HelperResult)' has some invalid arguments.

How can solve this? Any other option to add error message in ModelState on MVC using Javascript?

asked Jul 13, 2013 at 7:49

1 Answer 1

10

Well, I don't think you can write to the ModelState Dictionary using JavaScript because it is a Client-Side language and C# / Razor are processed on the Server-Side.

In the code you posted, the line

@Model.modelSateClientSide.AddModelError(string.Empty, "xxx");

Will actually be evaluated every time the page loads because it is processed on the server, and Razor doesn't "know" about JavaScript or its conditional statements.

If you, however, just want to display an error message similar to what the ValidationSummary HtmlHelper generates by default, you can write a JavaScript function to do it. Something more or less like this:

function showClientError(message) {
 var $div = $('.validation-summary-errors');
 if ($div.length == 0) {
 $div = $('<div class="validation-summary-errors">');
 $div.html('<ul></ul>');
 // Put the $div somewhere
 $div.appendTo($('#myForm'));
 }
 $div.find('ul').append($('<li>').text(message));
}
answered Jul 20, 2013 at 1:06
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.