简体   繁体   English

ASP.NET MVC在部分视图中使用javascript值

[英]ASP.NET MVC Use javascript value in partial view

I have a view with some javascript in it. 我有一个带有一些javascript的视图。 The javascript has a callback function that is called, when the data i need is ready (from indexeddb). 当我需要的数据准备就绪(来自indexeddb)时,javascript具有一个回调函数。

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). 我似乎无法使用ViewData,因为ViewData会在页面呈现后立即过期(因此,在收到回调之前)。 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. 您正在将服务器端代码与JavaScript混合在一起。 You cannot set ViewBag from JavaScript. 您无法通过JavaScript设置ViewBag

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. 相反,您需要对Controller Action(或Service Workers )进行AJAX POST/GET调用,然后作为响应,获取PartialViewJSON Data并在主视图中使用它。

UPDATE: OP confirmed that AJAX call is supported by Service Worker's Fetch event. 更新: OP确认Service Worker的Fetch事件支持AJAX调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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