簡體   English   中英

單擊按鈕時未定義javascript函數錯誤

[英]javascript function not defined error on click on a button

想象下面的MVC父模型:

模型:

Namespace MyProject.SampleModel
{
     public class ViewModelExample {
           public FirstModel BoolValues { get; set; }
           public SecondModel NamesValues { get; set; }
     }
}

Namespace MyProject.SampleModel
{
   public class FirstModel
   {
     public bool MyBoolean1 { get; set; }
     public bool MyBoolean2 { get; set; }
   }

   public class SecondModel
   {
     public string FirstName { get; set; }
     public string LastName { get; set; }
   }
}

視圖:

@model MyProject.SampleModel.ViewModelExample

@using (Html.BeginForm("MyAction", "MyController", FormMethod.Post, htmlAttributes: new { id = "Myform" }))
{

   (...)

   @Html.CheckBoxFor(m => m.BoolValues.MyBoolean1)

   (...)

    <input id="submitButton" type="button" value="Add" onclick="InitiateSequence();" />

   (...)
}

<script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script>
<script type="text/javascript">

      (...)

      function InitiateSequence()
      {
            // Do some stuff
      }

      (...)
      function ScriptSample() {

            if(@(Model.BoolValues.MyBoolean1 ? "true" : "false")
            {
                 // It's true, do some stuff
            }
            else
            {
                 // It's false, do some stuff
            }
      }

</script>

控制器:

public ActionResult MyAction(ViewModelExample model)
        {
            model.FirstModel = new TestsModel(); // I do not instantiate SecondModel as in the view for this controller i do not use it

            return View(model);
        }

頁面正確加載,但是當我單擊按鈕時,它說沒有定義javascript函數InitiateSequence...。這是怎么回事?

那可能是因為該功能最有可能出現在不應出現的位置。 另外,請勿使用內聯屬性來綁定處理程序,而應使用事件綁定而不是內聯處理程序。

<input id="submitButton" type="button" value="Add" />

<script type="text/javascript">

  (...) //whatever code

  $(function(){
     $('#submitButton').on('click', InitiateSequence);
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM