[英]Razor Core 2.2: set cshtml element as variable
在我看来,我想将部分视图分配给一个变量,然后我可以在 javascript function 中使用该变量。 有没有好的方法来做到这一点?
所以,我想做类似的事情:
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>
您可以从 controller 返回 PartialView 并显示在 ajax 的成功 function 中,下面是一个简单的演示,您可以参考:
产品 Model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}
主视图:
@model IEnumerable<Product>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
<button class="btnAdd" onclick="GetProduct(@item.Id)">Add To Cart</button>
</td>
</tr>
}
</tbody>
</table>
<div>
<label>ProductCart</label>
<table id="table">
<thead>
<tr>
<th>
Name
</th>
<th>
Price
</th>
<th></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
@section Scripts
{
<script type="text/javascript">
function GetProduct(id) {
$.ajax({
type: "get",
url: "/home/getpartial?id="+id,
success: function (result) {
console.log(result);
$("#table tbody").append(result);
}
});
}
</script>
}
部分视图:
@model Product
<tr>
<td>
@Html.DisplayFor(model => model.Name)
</td>
<td>
@Html.DisplayFor(model => model.Price)
</td>
</tr>
Controller:
public async Task<IActionResult> Products()
{
var products =await _context.Products.ToListAsync();
return View(products);
}
public IActionResult GetPartial(int id)
{
var model = _context.Products.Find(id);
return PartialView("_ItemPartial", model);
}
结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.