单击按钮时,javascript函数未定义错误

时间:2013-09-21 20:51:57

标签: javascript asp.net-mvc asp.net-mvc-4 razor

想象一下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没有定义....发生了什么?

1 个答案:

答案 0 :(得分:4)

这可能是因为很可能该功能出现在它不应该出现的地方。另外,不要使用内联属性来绑定处理程序,而是使用事件绑定而不是内联处理程序。

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

<script type="text/javascript">

  (...) //whatever code

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