简体   繁体   English

如何从ASP.NET MVC操作方法返回JSON对象

[英]How to Return a JSON Object from an ASP.NET MVC Action Method

When I'm in a controller, I need to pass an entity object ( Product ) back to a view for use in JavaScript. 当我在控制器中时,需要将实体对象( Product )传递回视图以在JavaScript中使用。

I pass a model object from the action method to the view. 我将模型对象从action方法传递给视图。 The model object contains some data the view needs for display, but also (the bit I'm struggling with) a JSON version of the product data. 模型对象包含视图需要显示的一些数据,还包含(我正在努力的)产品数据的JSON版本。

In the view, I want to pick up the product object as JavaScript to play with. 在视图中,我想将产品对象用作JavaScript。

Controller: 控制器:

public ActionResult ViewProduct( int  productKey )
{
    VendorPage page = PageManager.Instance().GetProductPage( );
    Product product = this.repoProducts.Get<Product>( App.GetVendorKey(), productKey );

    JavaScriptSerializer    sz = new JavaScriptSerializer();
    string json = sz.Serialize( new { pr = product } );

    ProductPageModel  ppm = new ProductPageModel( page, product );
    // Embed the product as json in the model
    ppm.js = json;

    if ( product != null )
    {
        return View( "Product", ppm );
    }
    return null;
}

View - uses the model as ProductPageModel @model SiteEngine.SiteEngineUI.Models.ProductPageModel html...... 视图-将模型用作ProductPageModel @model SiteEngine.SiteEngineUI.Models.ProductPageModel html ......

So, the question is: How do I gain access to the product in JavaScript, in order to do something like ... 因此,问题是:如何执行JavaScript中的产品访问权限,以便执行类似...

alert( product.Name );

Try this on View: 在View上尝试:

<script type="text/javascript">
  var product = jQuery.parseJSON(@Model.js);
</script>

in case you don't use jQuery, take a look at http://www.json.org/js.html 如果您不使用jQuery,请访问http://www.json.org/js.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM