javascript - .NET MVC 如何在 Javascript 中检索模型?

标签 javascript asp.net-core asp.net-core-mvc

我有一个来 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/

相关文章:

configuration - 如何在发布文件中设置 aspnetcore_environment?

c# - 使用 TryUpdateModel 时的 asp.net core mvc Controller 单元测试

c# - ASP.NET MVC 6 中的 TryValidateModel

razor - 从 ASP.NET Core 1.0 中的 ViewModel 元数据输入占位符

javascript - 在下面添加行时更改单元格值

javascript - jQuery 选项卡标题

javascript - 设置下载路径

JavaScript 是否给定的字符串作为变量和函数存在

asp.net-core - asp.net core 中的剑道配置

c# - asp.net core i3.0 web api request.body 和 [frombody] 冲突