How know if ModelState contains errors - javascript

When a form is posted in my controller, I make the following check:
if(ModelState.IsValid)
If the model is not valid, errors are added to the ModelState. The model is then passed to the view with validation summary.
However, I want to check if the ModelState has errors from inside the jQuery ready handler, so that I can add some additional behavior if the form has errors. Is that possible?

You could spit global javascript variable:
<script type="text/javascript">
var isValid = #Html.Raw(Json.Encode(ViewData.ModelState.IsValid));
</script>
and then:
$(function() {
if (!isValid) {
alert('opa');
}
});

a little addition to #Dimitrov answer:
<script type="text/javascript">
var isValid = '#Html.Raw(Json.Encode(ViewData.ModelState.IsValid))';
if (isValid != 'true')
// model has some errors...
</script>
It's important to use single qoutes around the helper. Otherwise, that ending semicolon ; cause problems. Nether you can write it, nor you can't, at all cases it cause a syntax error. Unless you put those single quotes around the helper as I mentioned.

In addition to Darins Answer:
In .cshtml:
#Html.Hidden("IsValid", Json.Encode(ViewData.ModelState.IsValid))
in JS
var isValid = $('#IsValid').val().toLowerCase() == "true";

Related

How to test a Javascript whether a form is submitted?

I am trying to test some of my javascript with Jasmine.
I am a newbie when it comes to Jasmine and my knowledge about Javascript is at best basic. What I want to do is to make sure the form is submitted. I can't figure out how the syntax for the tests should look like. I guess I need to use spyOn, but I'm not quite sure how. I would love it if someone could point me in the right direction.
function submitform(array) {
var token = array[0].replace("access_token=", "");
if ((token !== "")) {
$('input[name=Token]').val(token);
var frm = document.getElementById("tokenform");
frm.submit();
}
}
To test that frm.submit() was called you have to mock it. There are two ways to to it. The first way would work without code changes by spying on document.getElementById, this will work in your example as you only use it once, it will be harder if use document.getElementById more often.
var submit;
beforeEach(){
// when your code calls document.getElementById it return an object
// with just one property where you can spy on that it was called
submit = jasmine.createSpy();
spyOn(document 'getElementById').andReturn({submit:submit})
}
it ("should submit", function(){
submitform([somedata]);
expect(submit).toHaveBeenCalled();
})
The better way is to rewrite your code for better testability. So instead of getting the form by calling a DOM function, inject the form into your function as an argument. Now you can just pass the mock into your function instead of mocking document.getElementById. This pattern is also known as Dependency Injection
function submitform(array, frm) {
var token = array[0].replace("access_token=", "");
if ((token !== "")) {
$('input[name=Token]').val(token);
frm.submit();
}
}
it ("should submit", function(){
var submit = jasmine.createSpy();
var form = {submit: submit}
submitform([somedata],form);
expect(submit).toHaveBeenCalled();
})

Error when accesing Razor Boolean variable in Javascript

I have tried several tactics to use the boolean value within the JS ,but nothing works :
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
if (model.IsNew == true) {
alert("1");
}
</script>
Tried the following:
var IsNew = #Model.IsNew ;
var IsNew = "#Model.IsNew";
I keep getting the following error :
Conditional compilation is turned off
Anyone could explain why this occurs and maybe guide me to a possible solution ?
Try
if ('#Model.IsNew' == 'true') {
alert("Is New");
}
That's just the VS IDE failing to understand the mix of Razor and Javascript.
Your code will work fine.

Why my form doesn't validate the fields?

I can't see a clear mistake in this code. Instead of validating my fields, it just tries to send my form and I don't know why.
This is my jsFiddle: http://jsfiddle.net/PAALA/
Other question, how to validate if select box was picked?
Firstly, because of how JSFiddle works, defining a function with function foo() {...} is unreliable. Instead, use foo = function() {...} syntax.
Next, you have an error in your script when you try to access document.forms["bug_form"]["Project"].value - there is no text input with that name.
Finally, to prevent accidental submission, do this:
validateBugForm = function() {
try {
// ALL YOUR ORIGINAL CODE HERE
}
catch(e) {
alert("An error occurred: "+e);
return false;
}
}
This will ensure that false is returned, even if your code errs.
The Javascript code is crashing out on the third line when you try to get the value for "Project". Looks like you forgot to give that one a name.

__dopostback is not working in javascript function

am calling __dopostback function in javascript while closing event of browser but its not working in Chrome.
the same function is working in IE
can any one give me the solution.
<script type="text/javascript" language="javascript">
function doUnload()
{
var btnlogout = document.getElementById("ctl00_lbtn_Logout"); alert(btnlogout);
__doPostBack(btnlogout, '');
}
</script>
When doing a __doPostBack, you need to pass the control's UniqueID via javascript. ClientID will not work.
I think you should be passing the btnlogout id as string (not sure if you have to remove the ctl00 thing since it's a child control) as the function expects text and it is probably resolved during the request on the server..
Take a look at this article:
http://wiki.asp.net/page.aspx/1082/dopostback-function/
Just do:
btnlogout.click();
since you already have a reference to the button and, by the way, don't get the element the way you are doing it; do this instead:
var btnlogout = document.getElementById("<%=btn_Logout.ClientID%>");
dopostback(clientID, args)'s first parameter must be a control's clientid, it is a string , not object (of course string is object ) ..
in your case , i assume that is 'ctl00_lbtn_Logout', pass the right params like :
__doPostBack('<%= downloadUp.ClientID %>', current_index);
if your control is server side control, change 'downloadUp' to your control's id , else you just need pass the id
Please try to getElementById this way
var btnlogout = document.getElementById('<%= lbtn_Logout.ClientID %>');
alert(btnlogout)
and test it again , it will work..

Function not defined javascript

For some reason my javascript code is messed up. When run through firebug, I get the error proceedToSecond not defined, but it is defined!
JavaScript:
<script type = "text/javascript">
function proceedToSecond () {
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").style.visibility="visible";
}
function reset_Form() {
document.personalInfo.reset();
}
function showList() {
alert("hey");
if (document.getElementsById("favSports").style.visibility=="hidden") {
document.getElementsById("favSports").style.visibility="visible");
}
}
//function showList2() {
//}
</script>
HTML:
<body>
<!--various code -->
<input type="button" onClick="proceedToSecond()" value="Proceed to second form"/>
</body>
The actual problem is with your
showList function.
There is an extra ')' after 'visible'.
Remove that and it will work fine.
function showList()
{
if (document.getElementById("favSports").style.visibility == "hidden")
{
// document.getElementById("favSports").style.visibility = "visible");
// your code
document.getElementById("favSports").style.visibility = "visible";
// corrected code
}
}
There are a couple of things to check:
In FireBug, see if there are any loading errors that would indicate that your script is badly formatted and the functions do not get registered.
You can also try typing "proceedToSecond" into the FireBug console to see if the function gets defined
One thing you may try is removing the space around the #type attribute to the script tag: it should be <script type="text/javascript"> instead of <script type = "text/javascript">
I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.
important: in this kind of error you should look for simple mistakes in most cases
besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.

Categories