0

When I'm in a controller, I need to pass an entity object (Product) back to a view for use in JavaScript.

I pass a model object from the action method to the view. 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.

In the view, I want to pick up the product object as JavaScript to play with.

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......

So, the question is: How do I gain access to the product in JavaScript, in order to do something like ...

alert( product.Name );
2
  • 3
    Have you tried changing the way you are returning, and trying to do it via JsonResult? Commented Nov 9, 2012 at 16:35
  • Not sure how to, I need to goto the required view from the controller as this is not an ajax call. Commented Nov 9, 2012 at 17:14

1 Answer 1

1

Try this on 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

Sign up to request clarification or add additional context in comments.

6 Comments

thanks, I do use jQuery, but didn't see parseJSON. After some debug it does seem to work with the JavaScriptSerializer from the controller, except for text which has an ampersand in it - this was giving me a parse error until I found the problem. The JavaScriptSerializer encodes ampersand (&) as \\u0026 whick kills the parser.
following on, there are serveral other js encoded characters in the text and they also cause the parseJSON to fail with invalid character. Is there a technique that gets round this?
in fact, the serialized string in the controller looks like :
"{\"AvProductKey\":246,\"VendorKey\":1}" // cut down version, but in the view, via product = $.parseJSON( '@(Model.js)'); the string looks like '{&quot;AvProductKey&quot;:246,&quot;VendorKey&quot;:1}'. The parser fails because of the &quot; i think.
try DataContractJsonSerializer instead on JavaScriptSerializer : msdn.microsoft.com/en-us/library/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.