0

Can someone help me out I'm new to jQuery, I would like to know how can I pass an object through from a controller action MVC

public ActionResult UserGroupSetting()
{
    UserGroupSetting setting = //some code to retrieve the settings
    ViewData["Theme"] = setting.Theme;
    ViewData["Image"] = setting.LogoImage;
    returnView(setting);
}

What I want its to get the Theme and the logo image, in a jQuery function, that I will use to update a class in a stylesheet, The theme object contains a colour in Hex form only for now.

If someone can please help me with the call to a jquery function and how will I expose both the image and the theme objects in jquery.. Thanks

2
  • sorry for the being in line with my question, couldnt get it to be structured properly here. Commented May 14, 2012 at 20:40
  • You can't pass server objects directly to a javascript function. What you could do however, is make an Ajax call from the loaded page to the server that would return the objects Commented May 14, 2012 at 20:49

3 Answers 3

3

You can return the data in jSon format and let jquery make a call to your action method with getJSON method

public ActionResult UserGroupSetting()
{
   var result=new { Theme="YourTheme", Logo="YourLogoURL"};
   return Json(result, JsonRequestBehavior.AllowGet);
}

In your page,Call this from your javascript

$(function(){
   $.getJSON('YourController/UserGroupSetting', function(data) {
      alert(data.Theme);
      alert(data.Logo);
   });
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Shyju, will try this and let you know how it goes.
Thanks again shyju it works perfectly, I tried this for only the theme coz it was giving an error abt the size of the logo image, i will sort that one out, but thanks again ;).
1

if i were you , i would do this:

you can use ViewBag: in action: ViewBag.Setting = setting;

  UserGroupSetting setting = //some code to retrieve the settings
  ViewBag.Theme  = setting.Theme;
  ViewData.Image = setting.LogoImage;
  returnView(setting);

then in Razor:

 @{
    var setting = (UserGroupSetting)ViewBag.Setting;
  }

output it to javascript tag:

  <script type="text/javascript">
        var setting = new setting{
                 Theme = @setting.Theme,
               Image = @setting.Image
        }
  </script>

Comments

0

This may not be the best solution, but one option I've used in the past is to create a hidden input in your view and access the value of the input in your jQuery code. This would be an example of the code you would have in your view:

<input id="someID" type="hidden" value="@TempData["Theme"]" />

Comments

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.