每次使用ajax呈现部分视图时运行jquery代码

时间:2014-05-08 07:37:09

标签: jquery ajax asp.net-mvc datepicker

我使用Ajax.Actionlink在MVC中渲染部分视图。我还使用了Modernizr datepicker,因此firefox可以和Chrome一样好用输入类型= date。

当我点击我的第一个Ajax actionlink时,datepicker工作正常。但是,当我再次点击它时,它根本不起作用。

如果我重新加载页面(F5),它会再次起作用,第一次,而不是第二次以后。

我如何修复它以便每次运行jQuery代码,即使我切换到另一个局部视图?

我的JS:

<script>
    $.noConflict();  
    if (!Modernizr.inputtypes.date) {
        $('input[type=date]').datepicker({ dateFormat: 'yy-mm-dd' });
    }
</script>
编辑:我已尝试在$(function(){...})中包装JS;并且代码在局部视图内。也尝试使用OnSuccess选项,但结果是相同的。它只在第一次运行,之后我需要重新加载页面

编辑2:

我的Ajax actionlinks:

<div id="createCalcMenu">
@Ajax.ActionLink("Annuity", "Annuity", "Calculation", new AjaxOptions
        {
             UpdateTargetId = "calcDiv",
             InsertionMode = InsertionMode.Replace,
             HttpMethod = "POST"
        })
                    <br />              
@Ajax.ActionLink("Amortization", "Amortization", "Calculation", new AjaxOptions
        {
             UpdateTargetId = "calcDiv",
             InsertionMode = InsertionMode.Replace,
             HttpMethod = "POST"
        })
</div>
    <div id="calcDiv"></div>

编辑3:

我的部分观点:

@using (Ajax.BeginForm("ShowDetailAnnuity", "Calculation", new AjaxOptions
{
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "CalcDetail",
    LoadingElementId = "Loader"
}))
{
<input type="date" id="StartDate" name="startdate" title="Please enter start date (YYYY-mm-dd)" class="startDateTextbox" required />

//Rest of the form here...

<input type="submit" id="calcBtn" class="calcBtn" name="SubmitValue" value="Calculate" title="Calculate your calculation" />
}


<script>
$(function () {
    $.noConflict();
    if (!Modernizr.inputtypes.date) {
        $('input[type=date]').datepicker({ dateFormat: 'yy-mm-dd' });
    }
});
</script>

1 个答案:

答案 0 :(得分:1)

我认为问题可能出在jQuery

我复制了你的代码,只是对局部视图的脚本进行了一些小改动。 当我第一次运行代码时,它给了我一个错误,说$ $未定义(虽然我已将jQuery库包含在主布局中)。 我在部分布局中手动调用了jQuery并且它工作正常。我希望它可以帮助你。

以下是我在Annuity局部视图代码中所做的更改:

<script>
    jQuery(function ($) {
          $.noConflict();
          if (!Modernizr.inputtypes.date) {
              $('input[type=date]').datepicker({ dateFormat: 'yy-mm-dd' });
          }
    });
</script>

无论我点击链接多少次,datepicker总是为我而来。还要确保只有一次(在主布局中)对JS文件jquery和mordernizr的引用