在我看来,我想为变量分配部分视图,然后可以在javascript函数中使用它。有什么好方法吗?
所以,我想做类似的事情:
var foo = <partial name="_partial.cshtml"/>
然后我可以稍后使用foo
,例如:
<script>
$("#button").on("click", () => $("#table tbody").append(@foo));
</script>
您可以将局部变量保存在c#变量中,并在单击按钮时获取它。
C#:
@{
IHtmlString partialView = Html.Partial("yourview", yourmodel);
}
Javascript:
<script>
var partialView = `@partialView`;
$("#button").on("click", () => $("#table tbody").append(partialView));
</script>
您可以从控制器返回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");
}
结果: