gpt4 book ai didi

jquery - 如何在 mvc4 web api 中使用 <script> 标签设置值?

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:59 24 4
gpt4 key购买 nike

我正在使用 mvc4 web api 元素并希望在同一页面上绑定(bind)三个不同的 div

Detail.cshtml
$.getJSON(
"/api/GroupDetailValue/" + id,
function (data) {
$.each(data, function (index, value) {
if (value.Id != undefined) {
$("#GroupTemplate").tmpl(value); //I did like this to set all values to following div
}
});



<script id="GroupTemplate" type="text/html">
<div class="container">
<div class="span12">
Name</div></div>
<div class="container">
<div class="span8">
Memeber List</div></div>
<div class="container">
<div class="span3">
Address </div></div>
</script">

Not setting up values :( Getting runtime error :

0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'tmpl'

最佳答案

首先引用如下 JS 脚本 -

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js" type="text/javascript"></script>

那么您的模板应该包含这样的占位符 -

<script id="productstmpl" type="text/x-jquery-tmpl">
<li><b>Name</b> ${Name}</li>
</script>

然后让你的 JQuery GET 调用像这样 -

<script>
var uri = 'http://localhost:23133/api/products';
$.getJSON(uri,function (data) {
$.each(data, function (index, value) {
if (value.Id != undefined) {
$("#productstmpl").tmpl(value).appendTo("#me");
}
});
});
</script>

因此产品结果将填充到 div -

<div id="me">

</div>

在后端,为了支持以上所有代码,我有以下模型 -

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public decimal Price { get; set; }
}

Controller 的 Action 如下 -

public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};

public IEnumerable<Product> GetAllProducts()
{
return products;
}
}

当我执行我的页面时,我将通过以下方式获得结果 -

enter image description here

关于jquery - 如何在 mvc4 web api 中使用 &lt;script&gt; 标签设置值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21495033/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com