为什么我会收到“$ is not defined”错误?

时间:2011-12-30 15:25:45

标签: c# javascript knockout.js

我有一个ActionResult TabNotes,它返回一个选项卡的视图,该选项卡显示网格中数据库的注释。选项卡上有一个ActionResult CreateNote按钮,它返回一个PartialView,保存注释后我重定向回到ActionResult TabNotes

 return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});

但是,当它使用此重定向转到操作结果TabNotes时,它不会显示网格。 javascript给出以下错误

Uncaught ReferenceError: $ is not defined (anonymous function)
Uncaught ReferenceError: ko is not defined (anonymous function)

第一次进入ActionResult时不会发生这种情况。使用断点ActionResult TabNotes的以下部分:

[...]
   Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
    }

   return View("TabNotes", Model);
 }

第一次和第二次在Model中给出相同的输入值。这个错误来自哪里?

编辑:Firebug显示以下错误:

prompt aborted by user
throw Components.Exception...by user", Cr.NS_ERROR_NOT_AVAILABLE);        nsPrompter.js (regel 462       <Systeem>

$ is not defined
$(document).ready(function(){$('#tblTN...tes/44?cmd=refresh" id="TNPhrase44">        44?mod...=Phrase (regel 2)

ko is not defined
var viewModel=ko.mapping.fromJ...],"buttons":[],"PostAction":null}});           44?mod...=Phrase (regel 12)

以下是javascript和代码

@model test.Web.Framework.Areas.Administration.Models.TabNotesModel 
@using (UI.DocumentReadyScript())
{

    if (Model.meta.id.HasValue)
    {
        UI.jQuery("#tbl" + Model.meta.modelname).flexigrid(Model.Grid);
    }
}
<form method="post" action="@Url.Action("TabNotes", new { cmd = "refresh" })" id="@Model.meta.modelname">
<div class="ui-state-highlight ui-corner-all highlight" data-bind="visible: meta.message">
    <span class="ui-icon ui-icon-info"></span><strong data-bind="text: meta.message">
     </strong>
</div>
@using (UI.BeginBlock("Administation.TabNotes", UI.Label("Notes", "Notes").ToString(), test.Web.Framework.Core.enumIcons.pencil, false, false))
{
    <table id="@("tbl" + Model.meta.modelname)">
    </table>
}
</form>
<script type="text/javascript">
    (function() {
        var viewModel=ko.mapping.fromJS(@Html.Raw(UI.JavascriptEncode(Model)));
        viewModel.getData=function() { return ko.mapping.toJSON( this  ); };   
        viewModel.setData=function(data){ 
         $('#tbl'+this.meta.modelname()).flexigrid( data.Grid);
         ko.mapping.updateFromJS(this,data); 
         };
        $('#@Model.meta.modelname').koform({viewmodel: viewModel , validate : {errorElement:'p' }  } );
        $('#@Model.meta.modelname').koform('applyBindings');
        $('#load-partial').click(function() {
            $('#partial').load('@Url.Action("CreateNote", "Entity", new {itemId = @Model.meta.id, modelEntity = "Phrase"})');
        });
        })();   
</script>


<div id="partial"></div>
<button type="button" id="load-partial">Create Note</button>

public ActionResult CreateNote(
        [ModelBinder(typeof(Models.JsonModelBinder))]
        NoteModel Model, string cmd, long? itemId, string modelEntity)
    {           
        if (cmd == "Save")
        {
            Model.meta.message = "Note saved";
            test.Database.User User = UserRepository.GetUser(1);
            Entity entity = NotesRepository.GetEntity("Phrase");
            NotesRepository.StoreNote(Model.subject, Model.text, User, entity, itemId);
            return RedirectToAction("TabNotes", new { modelEntity = "Phrase", id = itemId});
        }
        Model.meta.modelname = "CreateNote";
        Model.meta.JsViewModelType = "EditNoteModel";
        Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId});


        return PartialView("CreateNotePartial",Model);

        }

    public ActionResult TabNotes([ModelBinder(typeof(Models.JsonModelBinder))]
        TabNotesModel Model, string cmd, string modelEntity, long? id)
    {
        if (modelEntity != null)
        {
            Model.meta.entity = modelEntity;
        }
        Entity entity = NotesRepository.GetEntity(Model.meta.entity);
        if (id.HasValue)
        {
            Model.meta.id = id;
        }

        if (Model.meta.id.HasValue)
        {
            Model.meta.modelname = "TN" + Model.meta.entity + Model.meta.id.Value.ToString();

            Dictionary<string, object> defaultValues = new Dictionary<string, object>();
            defaultValues.Add("Entity", entity.EntityId);
            defaultValues.Add("ItemId", Model.meta.id.Value);
            Entity noteEntity = NotesRepository.GetEntity("Note");
            var grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);
            grid.buttons.Clear();
            //grid.buttons.Add(new Button { onpress = "CreateNote", action = Url.Action("CreateNote"), name = "CreateNote", postdata = new { meta = Model.meta }});
            grid.title = "";
            Model.Grid = grid;

            Model.Grid.url = Url.Action("TabNoteData", new { id = Model.meta.entity, itemId = Model.meta.id.Value});
        }


       return View("TabNotes", Model);
    }

public GridResult TabNoteData(string id, long itemId, FlexigridRequest request, string cmd)
    {

        GridResult returnValue = null;


        var entity = NotesRepository.GetEntity(id);
        Entity noteEntity = NotesRepository.GetEntity("Note");
        //var Acess = UIRepository.GetEntityAccess(id);

        FlexigridConfiguration grid;
        Dictionary<string, object> defaultValues = new Dictionary<string, object>();
        defaultValues.Add("Entity", entity.EntityId);
        defaultValues.Add("ItemId",itemId);
        grid = UI.GetEntityFlexiGrid(noteEntity, true, true, true, true, defaultValues);

        IQueryable q = NotesRepository.GetNotes(entity.EntityId, itemId);
        var sortField = entity.EntityFields.SingleOrDefault(c => c.Name == request.sortname);
        if (sortField == null)
        {
            request.sortname = grid.sortname;
        }
        IQueryable qdata = null;
        if (!string.IsNullOrEmpty(request.sortname) && request.sortname != "undefined")
        {
            switch (request.sortorder)
            {
                case enumFlexigridRequestSortOrder.asc:
                    qdata = q.OrderBy(request.sortname + " ascending");
                    break;
                case enumFlexigridRequestSortOrder.desc:
                    qdata = q.OrderBy(request.sortname + " descending");
                    break;
            }
        }
        if (!string.IsNullOrEmpty(request.query) && !string.IsNullOrEmpty(request.qtype))
        {
            qdata = qdata.Where(request.qtype.SanitizeFieldExpression() + ".Contains(@0)", request.query);
        }
        if (request.q != null && request.q.Length > 0)
        {
            for (int i = 0; i < request.q.Length; i++)
            {
                var type = UIRepository.GetType(id);
                var property = type.GetProperty(request.q[i]);

                System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(property.PropertyType);
                string sv = request.v[i];
                if (sv == null || sv == "null")
                {
                    qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=@0", (object)null);
                }
                else
                {
                    object v = tc.ConvertFromString(sv);
                    qdata = qdata.Where(request.q[i].SanitizeFieldExpression() + "=@0", v);
                }
            }
        }


        string settingName = "Grid." + id + ".Rp";
        var setting = UIRepository.GetQuery<test.Database.UserSetting>().SingleOrDefault(uc => uc.CreatedById == CurrentUser.UserId && uc.Name == settingName);
        if (setting == null)
        {
            setting = UIRepository.Create<test.Database.UserSetting>();
            setting.Name = settingName;
            setting.Value = request.rp.ToString();
            UIRepository.Add(setting);
        }
        else
        {
            if (request.rp.ToString() != setting.Value)
            {
                setting.Value = request.rp.ToString();
                UIRepository.Update(setting);
            }
        }

        int rowId = 0;
        var datarows = new List<object>();
        foreach (var record in qdata.Skip((request.page - 1) * request.rp).Take(request.rp).GetData())
        {
            var cellValues = new List<object>();
            foreach (var gc in grid.colModel.OrderBy(c => c.di))
            {
                cellValues.Add(gc.ToString(UI, record));
            }
            var row = new { id = rowId, cell = cellValues.ToArray() };
            datarows.Add(row);
            rowId++;
        }
        returnValue = Grid(request.page, qdata.Count(), datarows.ToList());

        return returnValue;
    }

1 个答案:

答案 0 :(得分:2)

该错误只能导致以下三种情况之一:

  • 您的JavaScript文件未正确加载到您的页面中
  • 你有一个拙劣的jQuery版本。这可能是因为有人编辑了核心文件,或者插件可能覆盖了$ variable。
  • 在页面完全加载之前,您已经运行了JavaScript,因此,在jQuery完全加载之前。

您应该检查Firebug网络面板以查看文件是否实际正在正确加载。如果没有,它将突出显示为红色并在其旁边显示“404”。如果文件正确加载,则表示问题是数字2。

确保所有javascript代码都在代码块中运行,例如:

$(document).ready(function () {
  //your code here
});

这将确保在初始化 jQuery之后加载代码。

要检查的最后一件事是确保在加载jQuery之前没有加载任何插件。插件扩展了“$”对象,所以如果你在加载jQuery核心之前加载插件,那么你将得到你描述的错误。

所以为了避免你可以使用如下所示的“保镖”功能:

( function($) {
   //We can now use $ as I implemented the bodyguard!
   $(document).ready(function() {
      //your code...
   });
} ) ( jQuery );