简体   繁体   中英

How to pass an object from a mvc controller action to a view using jquery

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

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM