如何在ASP.NET MVC中将视图模型转换为JSON对象? [英] How to convert View Model into JSON object in ASP.NET MVC?

查看:125
本文介绍了如何在ASP.NET MVC中将视图模型转换为JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java开发人员,刚接触.NET.我正在.NET MVC2项目中工作,我想在其中进行包装小部件的局部视图.每个JavaScript小部件对象都有一个将由模型数据填充的JSON数据对象.然后,当在窗口小部件中更改数据或在另一个窗口小部件中更改数据时,用于更新此数据的方法将与事件绑定.

I am a Java developer, new to .NET. I am working on a .NET MVC2 project where I want to have a partial view to wrap a widget. Each JavaScript widget object has a JSON data object that would be populated by the model data. Then methods to update this data are bound to events when data is changed in the widget or if that data is changed in another widget.

代码是这样的:

MyController:

virtual public ActionResult DisplaySomeWidget(int id) {
  SomeModelView returnData = someDataMapper.getbyid(1);

  return View(myview, returnData);
}

myview.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeModelView>" %>

<script type="text/javascript">
  //creates base widget object;
  var thisWidgetName = new Widget();

  thisWidgetName.updateTable = function() {
    //  UpdatesData
  };
  $(document).ready(function () {
    thisWidgetName.data = <% converttoJSON(model) %>
    $(document).bind('DATA_CHANGED', thisWidgetName.updateTable());
  });
</script>

<div><%:model.name%></div>

我不知道如何以SomeModelView的形式发送数据,然后能够使用它来填充小部件以及将其转换为JSON.我已经在控制器中看到了一些简单的方法,但是在视图中却没有.我认为这是一个基本问题,但是我已经花了几个小时试图使它变得如此光滑.

What I don’t know is how to send the data over as SomeModelView and then be able to use that to populate the widget as well as convert that to JSON. I had seen some real simple ways to do it in the controller but not in the view. I figure this is a basic question but I’ve been going for a few hours trying to make this slick.

推荐答案

在带有剃须刀@Html.Raw(Json.Encode(object))的mvc3中,似乎可以解决问题.

In mvc3 with razor @Html.Raw(Json.Encode(object)) seems to do the trick.

这篇关于如何在ASP.NET MVC中将视图模型转换为JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆