当通过部分视图返回页面时,JQuery函数函数不起作用

时间:2012-11-19 11:21:01

标签: asp.net-mvc asp.net-mvc-3 jquery partial-views

我将这个jquery函数放在我的.js文件中......只要我的页面被加载就可以了......但是当我改变它作为局部视图返回时......这个警告不再起作用了......怎么会再次工作?

  $(document).ready(function () {

    var msg = '@ViewBag.Message';

    if (msg == '1')
        alert("New Time Shift has been saved.");

});

在我的控制器动作......

   if (Request.IsAjaxRequest())
          return PartialView("_RecordList", userRecord); //alert wont work here...

   return View(userRecord); //this will return the whole view thus the alert works here

2 个答案:

答案 0 :(得分:1)

不会从ajax请求执行文档就绪功能。 您可以将javascript代码提取到整个视图的独立功能部分。您还可以创建一个回调函数,以便在部分请求成功时执行,也将调用它:

$(document).ready(function () {
    var msg = '@ViewBag.Message';
    initFunction(msg);
});

function initFunction(msg){
    if (msg == '1')
        alert("New Time Shift has been saved.");
}

function partialRequestSuccess(data){
    //store the message somewhere in the partial view, like a hidden div and get it using jquery
    var msg = ...
    initFunction(msg);
}

然后你可以设置ajax请求的完整回调来调用我们刚刚创建的成功回调。如果您正在使用MVC ajax助手,则可以设置一个Success参数,如:

@using(Ajax.BeginForm(new AjaxOptions{ OnSuccess = "partialRequestSuccess" }))

答案 1 :(得分:0)

I have this jquery function placed in my .js file....

var msg = '@ViewBag.Message';

这是服务器代码,仅适用于*.cshtml个文件,这是最小的一个问题。