Razor Core 2.2:将cshtml元素设置为变量

问题描述 投票:0回答:2

在我看来,我想为变量分配部分视图,然后可以在javascript函数中使用它。有什么好方法吗?

所以,我想做类似的事情:

var foo = <partial name="_partial.cshtml"/>

然后我可以稍后使用foo,例如:

<script>
    $("#button").on("click", () => $("#table tbody").append(@foo));
</script>
c# asp.net asp.net-core razor
2个回答
1
投票

您可以将局部变量保存在c#变量中,并在单击按钮时获取它。

C#:

@{
  IHtmlString partialView = Html.Partial("yourview", yourmodel);
}

Javascript:

<script>
    var partialView = `@partialView`;
    $("#button").on("click", () => $("#table tbody").append(partialView));
</script>

0
投票

您可以从控制器返回PartialView并将其显示在ajax的成功函数中,以下是您可以参考的简单演示:

查看:

<table id="table">
  <thead>
    //the stuff you want
  </thead>
  <tbody>

  </tbody>
</table>

<button id="button">Click</button>

@section Scripts
{
  <script type="text/javascript">
    $("#button").on("click", function () {
        $.ajax({
            type: "get",
            url: "/home/getpartial",
            success: function (result) {
                console.log(result);
                $("#table tbody").append(result);
            }
        });
    });
  </script>
}

Controller:

    public IActionResult GetPartial()
    {
        //more logic you want
        return PartialView("_TestPartial");
    }

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.