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?
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));
}