gpt4 book ai didi

javascript - 当我尝试在 JavaScript 中使用模型时模型为空

转载 作者:行者123 更新时间:2023-11-28 05:56:27 25 4
gpt4 key购买 nike

我的应用程序架构是 ASP.Net MVC我正在尝试使用 Entity Framework ORM 从 mssql 服务器传递一些数据。

这是我的操作的代码。

public ActionResult Create()
{
List<object> myModel = new List<object>();

var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());

myModel.Add(places);
myModel.Add(new Place());

ViewBag.UserId = new SelectList(db.AspNetUsers, "Id", "UserName");
return View(myModel);
}

我认为的代码

@model IEnumerable<object>

@{
List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;
WhereWeDoIt.Models.Place place = Model.ToList()[1] as WhereWeDoIt.Models.Place;
ViewBag.Title = "Create";
}

...

<script type="text/javascript">
//Users data
var json = @Html.Raw(Json.Encode(places));

console.log("Places test " + json);
</script>

...

控制台将输出“null”我做错了什么?

最佳答案

Once Html.Raw will get the string and put it directly in the html, try to put the @Html.Raw between single quotes like:

var json = '@Html.Raw(Json.Encode(places))';

Regards,

我上面提供的解决方案会将 json 设置为 json 字符串(而不是对象),因此不起作用,对此感到抱歉。下面是解决方案(在我的机器上模拟和测试)

嗯,我们这里发生了一些事情。

我已经在代码中取得了成功:

@model IEnumerable<object>

@{
var places = Model.ToList()[0];
HypothesisWebMVC.Models.Place place = Model.ToList()[1] as HypothesisWebMVC.Models.Place;
ViewBag.Title = "Create";
}

<script type="text/javascript">
//Users data
var json = @Html.Raw(Json.Encode(places));

console.log("Places test " + json);
</script>

此代码会将 json 变量设置为一个对象( Controller 中设置的地点列表)。

我不知道您的目标是什么,但我上面发布的代码可以工作。

一些注意事项:

在操作中,当您执行以下操作时:

    List<object> myModel = new List<object>();

var places = db.Places.Where(p => p.UserId == User.Identity.GetUserId());

myModel.Add(places);
myModel.Add(new Place());

您正在创建一个 myModel,该模型将在第一个位置和 Place 列表(或 IQueryable)中,在第二个位置中具有单个位置(不是列表),因此您无法将整个模型转换为列表.

您可以使用:

List<WhereWeDoIt.Models.Place> places = Model.ToList()[0] as List<WhereWeDoIt.Models.Place>;

通过,添加到模型时,在插入之前执行 .ToList()。

考虑使用 View 模型(专门为 View 创建的对象)

希望我能有所帮助。

问候,

关于javascript - 当我尝试在 JavaScript 中使用模型时模型为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37632789/

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