Reputation: 65
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
Upvotes: 0
Views: 723
Reputation: 1386
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>
Upvotes: 1
Reputation: 218732
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);
});
});
Upvotes: 3
Reputation: 1832
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"]" />
Upvotes: 0