我有一个来 self 的服务器的产品列表和一个客户对象。我想在 javascript 上检索该信息。
<!-- Customer object -->
<input type="hidden" id="customer" value="@ViewBag.Customer">
<!-- List of products -->
<input type="hidden" id="products" value="@Model">
现在在我的 javascript 中我有这个。
console.log(document.getElementById("customer").value);
这不起作用,我没有得到对象值。我想知道如何达到理想的结果?
源代码...
<!-- Customer object -->
<input type="hidden" id="customer" value="Namespace.Models.Customer">
<!-- List of products -->
<input type="hidden" id="products" value="System.Collections.Generic.List`1[Namespace.Models.Product]">
这是我的服务器端代码。
public async Task<IActionResult> Order(int customerId)
{
ViewBag.Customer = await customerRepository.Details(customerId);
var product = await productRepository.GetAll();
return View(products);
}
最佳答案
根据评论,您似乎想在 javascript 中读取整个模型对象,您可以使用 javascript 序列化器从模型创建一个 json 字符串。
这是一个使用的示例
<script>
var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
console.log(model);
</script>
变量model
将包含一个代表 Razor View 模型对象的js对象(字典样式)。
由于我们正在执行 C# 表达式/方法(Html.Raw
, SerializeObject
),因此上述代码必须位于 razor View 内,而不是外部 javascript 中文件(通过全局变量)。只要将 js 对象设置为全局变量后包含该文件,您仍然可以访问外部 js 文件内的对象
关于javascript - .NET MVC 如何在 Javascript 中检索模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50975240/