简体   繁体   中英

How can I get my javascript work in an asp.net cshtml file?

I have a html input for uploading a picture to my ftp, and I want my JS the detect changes on my button. My cshtml is:

    @using (Html.BeginForm("UploadFile", "Upload", FormMethod.Post, new { 
    enctype = "multipart/form-data" }))
    {

    <input id="uploadFile" placeholder="No file..." disabled="disabled" />
    <div class="fileUpload btn btn-primary">
        <span>Browse</span>
        <input id="uploadBtn" type="file" class="upload" />
    </div>
    <input type="submit" title="OK" />
} 

and my script is

<head>
<script type="text/javascript" language="javascript">
        document.getElementById("uploadBtn").onchange = function ()
        {
            document.getElementById("uploadFile").value = this.value;
        };
    </script>
</head>

When I run my code I get the following message:

0x800a138f - JavaScript runtime error: Unable to get property 'onchange' of undefined or null reference

I checked my html and JS in fiddle, everything works great, so I guess that Razor and JS have some problems with each others. Any tips?

Try this:

1.

<head>
<script type="text/javascript" language="javascript">

$(document).ready(function(){
        document.getElementById("uploadBtn").onchange = function ()
        {
            document.getElementById("uploadFile").value = this.value;
        };
});
    </script>
</head>
  1. As per @StephenMuecke : Move your script to immediately before the closing </body> tag (as my view it's best way)

    <body> .............. .............

     <script type="text/javascript" language="javascript"> $(document).ready(function(){ $('#uploadBtn').on('change', function() { $("#uploadFile").val($(this).val()); }) }); </script> 

    </body>

3.If you use separate script ( .js file) then try

     $(document).on('change','#uploadBtn' ,function() {
         $("#uploadFile").val($(this).val());
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM