0

当我在控制器中时,我需要将实体对象 ( Product) 传递回视图以在 JavaScript 中使用。

我将模型对象从动作方法传递给视图。模型对象包含视图需要显示的一些数据,而且(我正在努力解决的一点)产品数据的 JSON 版本。

在视图中,我想将产品对象作为 JavaScript 来使用。

控制器:

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

视图 - 使用模型作为 ProductPageModel @model SiteEngine.SiteEngineUI.Models.ProductPageModel html......

所以,问题是:我如何在 JavaScript 中获得对产品的访问权限,以便执行类似...

alert( product.Name );
4

1 回答 1

1

在视图上试试这个:

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

如果您不使用 jQuery,请查看http://www.json.org/js.html

于 2012-11-09T19:56:42.500 回答