views:

83

answers:

3

Hi,

Iam trying to pass data from my controller, and put it into the variable in JS script. I have done it before and it worked perfectly, thats why this one puzzles me even more.

Here is my code of the controller:

public ActionResult GetCategories()
        {
            var categories = categoryRepository.ListActiveCategories().ToList();
            return View(categories);
        }

And this is my JS code in the view:

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js"&gt;&lt;/script&gt;

<script type="text/javascript">
    var categories = JSON.parse('<%= Model %>');

</script>

And this is the output I get on my website in the browser:

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js"&gt;&lt;/script&gt;



<script type="text/javascript">

    var categories = JSON.parse('System.Collections.Generic.List`1[SklepOnline.Category]');







</script>

In chrome I also get an error "Uncaught SyntaxError: Unexpected token ILLEGAL". Any ideas what is wrong in this code? I am pretty sure it is the same I use for my other project and that one works just great so I really dont know what is wrong. Any help would be much appreciated.

Best Regards Bhaal275

A: 

You need to return JsonResult via Json method in controller.

gandjustas
Well not exactly, I had to parse the data to JSON and then send them to the view, but with the use of newly created class. But your advice pointed me the right way, thanks :)
Tromax
A: 

From what I gather, you are trying to return a JSON object from your action. If this is the case, you don't actually need a view for it at all. As long as your SklepOnline.Category object is serializable, you can return a Json representation of that object with an action like this:

public JsonResult GetCategories()
{
    var categories = categoryRepository.ListActiveCategories().ToList();
    return Json(categories);
}

Now, to consume this object, you can grab it with a simple AJAX call from your JavaScript within any view. This example uses jQuery:

$.getJSON('MyController/GetCategories', function(categories) {
    // now I have a JSON object called "categories" with my data
});

This saves you from having to write a view at all, and the data will be loaded via AJAX in the background. Good luck.

Scott Anderson
+1  A: 

You need to render a javascript string that can be parsed by JSON.parse(). Use JavaScriptSerializer to do that (this is an extention method for HtmlHelper):

public static IHtmlString ToJson(this HtmlHelper instance, object data)
{
    var serializer = new JavaScriptSerializer();
    return new HtmlString(serializer.Serialize(data));
}

Then in View:

var categories = JSON.parse('<%= Html.ToJson(Model) %>');

Don't use another controller action (as suggested by Scott Anderson) cause it requires another round-trip to the server.

Jakub Konecki