how to call .js method from index.cshtml

N.Kavin 20 Reputation points
2023-05-23T05:19:30.8766667+00:00

just i create a common toaster in index.cshtml. in that index file inside the script area .js method(for toast) mentioned

and .js source reference was added correctly and also that .js method was working in other child cshtml(index.cshtml is common layout). below here i given my code

in below code cm_toast is a java script method in .js file

 @if (Model.errors != null)
    {
        <script type="text/javascript">

            @foreach (var er in Model.errors)
            {
               
            cm_toast("warning", er.ErrorHeading, er.ErrorMessage);
            } 
         

        </script>
    }
Developer technologies ASP.NET Other
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2023-05-23T07:27:26.8933333+00:00

    Hi @N.Kavin,

    You need to pass the parameter as a string literal. Wrap it with single quotes or double quotes.

    If the function is inside an external js file, you need to make sure to include/load it before executing the method.

    @if (Model.errors != null)
    {
        foreach (var er in Model.errors)
        {
            <script src="~/area.js"></script>
            <script type="text/javascript">
                cm_toast("warning", '@er.ErrorHeading', '@er.ErrorMessage');                   
            </script>
        }
    
    }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-05-24T15:52:59.4766667+00:00

    a better approach is to pass the errors:

    <script type="text/javascript">
       const errors = @Html.Raw(JsonConvert.SerializeObject(Model.errors)) ?? [];     
       errors.forEach(er => cm_toast("warning", er.ErrorHeading, er.ErrorMessage));
    </script>
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.