开发者

ASP.NET MVC 2.0 How to pass data from controller to Jquery

开发者 https://www.devze.com 2023-01-17 03:48 出处:网络
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.

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"></script>

<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"></script>



<script type="text/javascript">

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







</开发者_如何学Goscript>

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


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.


You need to return JsonResult via Json method in controller.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消