1

I am trying to call a js function inside my view :

@model DomainClass.Group

@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
    <script language="javascript" type="text/javascript">
        document.read = function myFunction() {
            if (ViewBag.State == "error") {
                if (confirm("معیار مورد نظر دارای زیر مجموعه های مرتبط است. آیا تمایل به ویرایش دارید ؟")) { } else {
                    history.back();
                }
            }

        }
    </script>

}

    }
    @using (Html.BeginForm())
    {
       //my code 
    }

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

As you can see the my function name is myfunction and it depends on viewbag value ,but never it is't called by browser!!!

Should i add extra code to my view ?

Any ideas will be appreciated .

Best regards

1
  • @E A surely you just need a $(document).ready(function() {} which calls your function Commented Oct 3, 2014 at 9:19

1 Answer 1

2

Your Script is never executed because it won't be rendered to the page. So i moved it out of the server tags and into the HTML markup. Only filling in the parameter you need. But then you have a second problem. You sign the function to a variable on the window. No matter the name of the function on the right side it will be named the one on the left side. In fact, the right side shouldn't have a name al togheter. Then the third and final problem is, you don't call the function anywhere. Since i see that you included jquery validate i presume you also included jQuery and made use of their document ready function.

I've included an update of your function. There is some more room for optimalisation but it didn't include them to make it clear where your mistakes where.

@model DomainClass.Group
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script language="javascript" type="text/javascript">
    //use window instead of document
    window.myFunction = function () {
        //Try setting the boolean this way
        var x = @(ViewBag.State == "error" ? "true" : "false");
        if (confirm("معیار مورد نظر دارای زیر مجموعه های مرتبط است. آیا تمایل به ویرایش دارید ؟")) {

        }
        else {
            history.back();
        }
    }

    $(function () {
        window.myFunction();
    });
</script>
@using (Html.BeginForm())
{
    //my code
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't work,I need when the page is loaded my function be called .

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.