ASP.NET MVC Use javascript value in partial view

1.2k views Asked by At

I have a view with some javascript in it. The javascript has a callback function that is called, when the data i need is ready (from indexeddb).

This data, i want to pass to a partial view - How do i do that? I cannot seem to use ViewData, as that expires as soon as the page renders (thus, before the callback is received). Any ideas? Code is here:

<div>
    <script type="text/javascript">
        var somecallback = myFunctionDefinedSomewhere();
        somecallback.onsuccess = function(evt) {
            console.log("Success!");

            var iReallyNeedThisVariable = evt.id;
            @ViewData["iReallyNeedThisVariable"] = iReallyNeedThisVariable;
        }
    </script>

    @for (int i = 0; i < Model.MyCollection.Count; i++)
    {
        if (i == 0)
        {
            @Html.Partial("_MyPartialView", Model.MyCollection.ElementAt(i), new ViewDataDictionary { { "Stuff", true }, { "iReallyNeedThisVariable", @ViewData["iReallyNeedThisVariable"] } });
        }
        else
        {
            @Html.Partial("_MyPartialView", Model.MyCollection.ElementAt(i), new ViewDataDictionary { { "Stuff", false }, { "iReallyNeedThisVariable", @ViewData["iReallyNeedThisVariable"] } });
        }
    }
</div>
1

There are 1 answers

0
ramiramilu On BEST ANSWER

you are mixing Server side code with JavaScript. You cannot set ViewBag from JavaScript.

Instead you need to make a AJAX POST/GET call to Controller Action (or to the Service Workers), then in response either get PartialView or JSON Data and use it in your main view.

UPDATE: OP confirmed that AJAX call is supported by Service Worker's Fetch event.