在.NET CORE中将数据从视图传递到部分视图 [英] Passing Data from View to Partial in .NET CORE
问题描述
我阅读了此,并尝试在其中实现 ViewDataDictionary
我的应用程序无法正常工作。
I read this and tried to implement the ViewDataDictionary
in my app but did not work.
在我看来,我的代码如下:
In my view, I've the below code:
@{
var myTest = new
{
UserId = "cdb86aea-e3d6-4fdd-9b7f-55e12b710f78",
UserName = "iggy",
};
}
@Html.Partial("~/Partials/test.cshtml", myTest)
和 test.cshtml
非常简单,当我编写 @Model
时,我得到 {UserId = cdb86aea-e3d6-4fdd-9b7f-55e12b710f78,UserName = iggy}
and the test.cshtml
is very simple, when I write @Model
, I get { UserId = cdb86aea-e3d6-4fdd-9b7f-55e12b710f78, UserName = iggy }
我如何将其提取为JSON,这样我就可以读取 @ Model.UserName
How can I extract this as JSON, so I can read @Model.UserName
我尝试使用:
<script type="text/javascript">
@
{
<text>
var obj = JSON.parse(@Model);
</text>
}
</script>
并尝试:
<script type="text/javascript">
@:var obj = JSON.parse(@Model);
</script>
并尝试:
@Html.Raw(Json.Encode(object))
但没有任何作用
but nothing worked, any help!!
推荐答案
当我将.net应用程序转换为.net核心时遇到了类似的问题。
在.net中,我只需在控制器中 返回Json(jsonModel) ,然后在我的视图中将其用作 data.UserID , data.UserName (请参见下面的代码,以使其与示例匹配)。
在.net核心中,我必须首先在控制器中使用SerializeObject,然后在视图javascript部分中使用JSON.parse使其起作用。
I came across similar problem when I was converting my .net application into .net core. In .net I could just return Json(jsonModel) in my controller and use it in my view as data.UserID, data.UserName (see code below adjusted to match your sample). In .net core I had to SerializeObject in my controller first and then use JSON.parse in the view javascript section to make it work.
以下工作原理在.NET CORE中。假设您有某种模型:
The following works in .NET CORE. Assuming you have some model:
public class SomeModel
{
public string UserId { get; set; }
public string UserName { get; set; }
}
在您的控制器中返回Json对象:
in your controller return Json object:
using Newtonsoft.Json;
[HttpPost]
public IActionResult someAction()
{
SomeModel jsonModel = new SomeModel();
jsonModel.UserId = "cdb86aea-e3d6-4fdd-9b7f-55e12b710f78";
jsonModel.UserName = "iggy";
var serializedJsonModel = JsonConvert.SerializeObject(jsonModel);
return Json(serializedJsonModel);
}
,然后在视图javascript部分中可以从模型中检索值:
and in your view javascript section you can retrieve values from your model:
<script type="text/javascript">
$.post("@Url.Action("someAction", "YourController")",
function (data) {
var oJson = JSON.parse(data);
UserId = oJson.UserId;
UserName = oJson.UserName; });
</script>
这篇关于在.NET CORE中将数据从视图传递到部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!