Home > Software engineering >  Jquery - MVC - Functionname is not defined at HTMLButtonElement.onclick
Jquery - MVC - Functionname is not defined at HTMLButtonElement.onclick

Time:03-13

I searched this error and tried other people`s solution but it does not fixed.I changed jquery versions , write code from beginning vs vs but still same.

 [HttpPost]
    public JsonResult GetID(int ID)
    {
        List<User> users = db.users.ToList();
        User user = users.FirstOrDefault(x => x.Id == ID);
        return Json(user, JsonRequestBehavior.AllowGet);
    }



 <button onclick="dataget()" id="personID" style="margin-left: 28%;"> <span  style="font-size:30px" aria-hidden="true"></span></button>


<script type="text/javascript">

    var dataget = function () {
        var ID = 1;
        $.ajax({
            url: '/Finder/GetID/'   ID,
            type: 'POST',
            dataType: 'json',
            success: function (data) {
                $("#Name").html(data.Name);
                $("#Surname").html(data.Surname);
            }

        });
</script>

CodePudding user response:

Use this as your button;

<button id="personID" style="margin-left: 28%;">
   ...
</button>

You need to put your script inside a razor section, it will be inserted to script section in your layout.

@section script {
   <script type="text/javascript">

      // execute this function upon page ready
      $(document).ready(function(){

         // bind the event to your button
         $("#personID").click(function(e){
            e.preventDefault();
            
            //Fetch form data
            var sendData = { ID:1 };

            $.ajax({
               url: '@Url.Action("Find","GetID")',
               type: 'POST',
               data: sendData,
               dataType: 'json',
               contentType: 'application/json; charset=utf-8',
               success: function (data) {
                  $("#Name").html(data.Name);
                  $("#Surname").html(data.Surname);
               }
            });
         });
      });
   </script>
}
  • Related