简体   繁体   中英

ASP.NET MVC Use javascript value in partial view

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>

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.

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