Yasser Shaikh
Yasser Shaikh

Reputation: 47804

How to pass object in ViewBag which is to be used in jquery?

I am passing few values in ViewBag to my View which then has some jquery written to read and use it.

public ActionResult Update(int id)
{
    ViewBag.ProductId = id;
    var settings = _service.GetAdvancedSettings();
    ViewBag.Settings = settings;
    return View();
}

Just to give you an idea I have posted My Setting class which is returned from the GetSettings() method.

public class AdvancedSettings 
{
    public bool ShowName { get; set; }
    public bool ShowQuantity { get; set; }
    public bool ShowPrice { get; set; }
}

I am getting the following error.

enter image description here

I was able to read and use the int value of the "id" till now. How do I use the object and it values ?

Upvotes: 0

Views: 10205

Answers (4)

Alexey Ripenko
Alexey Ripenko

Reputation: 149

You can convert settings to json:

var settings = @(Html.Raw(Json.Encode(ViewBag.Settings)));

In this situation you should to create view model class that represents settings to avoid errors in the future if settings will be changed and can't be convertable to json.

Upvotes: 4

Yasser Shaikh
Yasser Shaikh

Reputation: 47804

Passing the value as model and then encoding it using System.Web.Helpers.Json worked. Here's a snippet of the code I used.

Controller

public ActionResult Update(int id)
{
    ViewBag.ProductId = id;
    var settings = _service.GetAdvancedSettings();
    ViewBag.Settings = settings;
    return View(settings);
}

View

@model AdvancedSettings

<script type="text/javascript">
    $(document).ready(function () {
       var jsonSettings = "@System.Web.Helpers.Json.Encode(Model)";
       var settings = JSON.parse(jsonSettings.replace( /&(lt|gt|quot);/g , '"'));

       console.log(settings);
    });
</script>
}

Upvotes: 0

monu
monu

Reputation: 370

Declare a Viewbag object in controller. Create a script var in View. Now that var you can use in your js file. Hete GetContainersUrl is of string having json value.

<script>
    var SELECTED_BLOBS = "@ViewBag.GetContainersUrl";
</script>

in js file use like this

if (SELECTED_BLOBS != "") {
        var obj = JSON.parse(SELECTED_BLOBS);
}

Upvotes: 0

Osman M Elsayed
Osman M Elsayed

Reputation: 810

Use a hidden input inside your view :

    <input type="hidden" id="AdvancedSettings_ShowName" value="@ViewBag.Settings.ShowName" />
    <input type="hidden" id="AdvancedSettings_ShowQuantity" value="@ViewBag.Settings.ShowQuantity" />
    <input type="hidden" id="AdvancedSettings_ShowPrice" value="@ViewBag.Settings.ShowPrice" />

Then call the values of those hidden inputs inside your js file :

var settings = {
    showName : $('#AdvancedSettings_ShowName').val(),
    ShowQuantity: $('#AdvancedSettings_ShowQuantity').val(),
    ShowPrice: $('#AdvancedSettings_ShowPrice').val()
}

Upvotes: 0

Related Questions