【问题标题】:Json object to C# model object in mvc ViewJson对象到mvc视图中的C#模型对象
【发布时间】:2018-05-23 17:27:56
【问题描述】:

我将 json 对象渲染为视图源的一部分。我想将该 json 转换为 C# 模型对象并将该对象传递给局部视图,因为局部视图被强类型化为模型对象。

例如:

jsonIdentifier = '{"Identifier": { "name":"uno","contextId":"dos"}}'

@{ model.Identifier = Parsing(jsonIdentifier)}
@Html.Partial("_IdentifierPartial", m=>m.Identifier) //where Identifier is the object needs to be passed to  _IdentifierPartial 

【问题讨论】:

标签: c# json asp.net-mvc asp.net-mvc-4


【解决方案1】:

您应该使用@Html.Action 而不是@Html.Partial。只需将 jsonIdentifier 作为字符串参数传入,然后使用 Json.NET 将其转换为适当类型的对象。

如..

Output my partial with that Json:
<div>
    @{
        string json = "{Make: \"Toyota\", Model: \"Camry\", Year: 2017}";
    }
    @Html.Action("RenderCarScreen", new { carJson = json });
</div>

您的网络方法看起来像这样...

    public ActionResult RenderCarScreen(string carJson)
    {

        Car car = Newtonsoft.Json.JsonConvert.DeserializeObject<Car>(carJson);
        return PartialView("CarScreen", car);
    }

【讨论】:

    【解决方案2】:

    我们可以在@Html.Action()@Html.Partial 的帮助下实现这一目标。 @Html.Action() 需要 action 方法,借助 action 方法渲染部分页面。 @Html.Partial() 不需要操作方法,基于它呈现页面的对象值。所以@Html.Partial()@Html.Action() 性能更好。

    using Newtonsoft.Json;
    @{
         string JsonStr = {\"user\":\"me\",\"payment_method\":\"card\",\"items_bought\":[{\"id\":\"001\",\"name\":\"desk\",\"delivered\":\"true\"},{\"id\":\"455\",\"name\":\"chair\","delivered\":\"false\"},{\"id\":\"234\",\"name\":\"mousepad\",\"delivered\":"false\"},{\"id\":\"135\",\"name\":\"cabinet\",\"delivered\":\"false\"}]}
         var JsonObject = JsonConvert.DeserializeObject<MyJSON>(JsonStr);
    }
    <div>
         @Html.Partial("_IdentifierPartial", JsonObject) 
    </div>
    

    上面的代码可以正常工作并满足您的要求。但这种方法不可取,最好将 json 字符串转换为控制器端的模型对象并将模型对象传递给视图。

    例如:

    @model ModelClass
    <div>
         @Html.Partial("_IdentifierPartial",Model.PartialModel)
    </div>
    

    上述方法在浏览器中渲染页面的速度要快得多。

    【讨论】:

      猜你喜欢
      • 2016-07-28
      • 1970-01-01
      • 2013-08-24
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2011-03-22
      • 2012-10-18
      • 1970-01-01
      相关资源
      最近更新 更多