Passing Data from View to Partial in .NET CORE

2019-09-10 22:35发布

问题:

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)

and the test.cshtml is very simple, when I write @Model, I get { UserId = cdb86aea-e3d6-4fdd-9b7f-55e12b710f78, UserName = iggy }

How can I extract this as JSON, so I can read @Model.UserName

I tried using:

<script type="text/javascript">
@
   {
      <text>
            var obj = JSON.parse(@Model);
      </text>
   }
</script>

and tried:

<script type="text/javascript">
      @:var obj = JSON.parse(@Model);
</script>

and tried:

@Html.Raw(Json.Encode(object))

but nothing worked, any help!!

回答1:

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.

The following works in .NET CORE. Assuming you have some model:

public class SomeModel
{
    public string UserId { get; set; }
    public string UserName { get; set; }
}

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);
 }

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>


回答2:

If you're only interested in JSON serialization of your anonymous type, you can simply declare the @model of the partial as object.

In your main view:

@{
    var myTest = new
    {
        UserId = "cdb86aea-e3d6-4fdd-9b7f-55e12b710f78",
        UserName = "iggy",
    };
}

@Html.Partial("~/Partials/test.cshtml", myTest)

And in your test.cshtml partial:

@model object

<script type="text/javascript">
    var obj = @Html.Raw(Json.Encode(Model));
</script>