Is it possible to use razor syntax in a javascript code in ASP.NET Core

Viewed 41

In my MVC project, I have a form to be filled out by the user. There is client-side validation in the view; if you leave input fields empty and hit the post button, You'd see validation tags for each input. On hitting the post button a message is to be shown to the user for posting. The problem is on hitting the button, Even without filling out the form, It still shows the message. I tried to check whether the Model is not null by using Razor Syntax in javascript code, But I failed. Any suggestion?

@model User

<form method="post">
--------a few input fields in a form-------
 <button id="button" type="submit" class="btn btn-lg btn-success">send</button>
</form>
<div class="submit-progress d-none">
    <label>be patient please...</label>
</div>
@section scripts{
    <partial name="_ValidationScriptsPartial" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.2.7/js/fileinput.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#button").click(function () {
               if(@Model != null){
                 $(this).prop("disabled", true);
                 $(".submit-progress").removeClass("d-none");
             }
        });
    </script>
}
1 Answers

When you send your HTML to the browser, your "@Model" takes a value that never change. Suppose that @Model is null, you send this code to the client:

    $(document).ready(function () {
        $("#button").click(function () {
           if(null != null){
             $(this).prop("disabled", true);
             $(".submit-progress").removeClass("d-none");
         }
    });

Every button click will have the same condition always. You need to do some AJAX invocation or PostBack to check if your Model continue been null.

Related