【问题标题】:Don't run javascript function in PartialView不要在 PartialView 中运行 javascript 函数
【发布时间】:2014-06-12 06:24:03
【问题描述】:

我在母版页中添加了一个 js 文件。并在视图中使用它。

<div class="control-group">
 @Html.LabelFor(model => model.Computers, new { @class = "control-label" })
 <div id="computersEditorRows" style="clear: both; margin-right: 30px; padding: 10px; border: 1px solid rgb(204, 204, 204);">
   @foreach (var item in Model.Computers)
    {
      Html.RenderPartial("_ComputersEditorRow", item);
    }

  </div>
  <a id="addItemcomputer" style="cursor: pointer;">AddItem</a>
 </div>

和js文件

$(document).ready(function () {
 $("#addItemcomputer").click(function () {
    $.get("/TechnicalOfficerService/AddComputerNewRow", function (data) {
        $("#computersEditorRows").append(data);

    }).fail(function (xhr, err) {
        alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
        alert("responseText: " + xhr.responseText);
    });
 });
})

但是当我在 Partialview 中使用它时,不要调用函数。我在局部视图中使用此 html 代码,但不要调用 $("#addItemcomputer").click

局部视图

@model PSYCO.Web.Sepid.ViewModels.ComputerViewModel
@using PSYCO.Web.Sepid.Helpers;
<div class="control-group">
@using (Html.BeginCollectionItem("Computers"))
{
   <div class="control-group">
        @Html.LabelFor(model => model.Computers, new { @class = "control-label" })
        <div id="computersEditorRows" style="clear: both; margin-right: 30px; padding: 10px; border: 1px solid rgb(204, 204, 204);">
            @foreach (var item in Model.Computers)
            {
                Html.RenderPartial("_ComputersEditorRow", item);
            }

        </div>
        <a id="addItemcomputer" style="cursor: pointer;">Add Item</a>
    </div>
  <a class="removeItemNationality" style="cursor: pointer;">Delete</a>
   }
 </div>

编辑

在局部视图中添加此部分。

 @section Scripts
 {
  <script>
   $(document).on("click","#addItemcomputer",function () {
     alert('d');
     })
   </script>
 }

【问题讨论】:

  • 那是什么错误。未调用脚本或 /TechnicalOfficerService/AddComputerNewRow 为 404
  • 我在视图中使用它,它是工作。但是当我在局部视图中使用它时,不要运行函数。
  • 局部视图中如何使用?
  • 在浏览器上右键单击并查看源代码你能在html中看到#addItemcomputer链接,我认为@using (Html.BeginCollectionItem("Computers")) 有一些问题并且其中的html没有得到渲染
  • 您不能在局部视图中使用部分。

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


【解决方案1】:

应该在 PartialView 中添加脚本。

在局部视图中使用脚本链接。

<script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>

或者在局部视图中使用脚本标签。(不能在局部视图中使用部分)

<script>
$("#addItemcomputer").click(function () {
$.get("/TechnicalOfficerService/AddComputerNewRow", function (data) {
    $("#computersEditorRows").append(data);

}).fail(function (xhr, err) {
    alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
    alert("responseText: " + xhr.responseText);
});
});
</script>

【讨论】:

    猜你喜欢
    • 2015-01-29
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多