简体   繁体   English

使用JavaScript在ASP.NET MVC中加载部分视图

[英]Loading a partial view in ASP.NET MVC using javascript

I have about 15 partial views that I need to display based upon user's menu tab selection. 根据用户的菜单选项卡选择,我需要显示大约15个局部视图。 Basically I have these 15 menu tabs on the side and based on user click for these tabs, I will be displaying the content for that tab on the page. 基本上,我在侧面上有这15个菜单选项卡,根据用户对这些选项卡的单击,我将在页面上显示该选项卡的内容。

Also I am using Knockout here. 我也在这里使用淘汰赛。

So I have these 15 Knockout observables ( self.tab_A(), self.tab_B(), ...self.tab_N() ) populated when the page first loads. 所以我在页面首次加载时填充了这15个Knockout观察值( self.tab_A(), self.tab_B(), ...self.tab_N() )。

The code I have is something like this. 我拥有的代码是这样的。 Here is the view. 这是视图。

<ul id="tabs">
    <li>
        <a data-bind="click: function(){ $root.ShowHideDiv(tab_A.id); }" style="cursor: pointer;">
           Tab A
        </a>
    </li>

    <li>
        <a data-bind="click: function(){ $root.ShowHideDiv(tab_B.id); }" style="cursor: pointer;">
         Tab B
        </a>
    </li>
    ...
    ...
</ul>   

The partial views are pre-loaded but hidden from from user's view. 部分视图已预加载,但从用户视图中隐藏。

<ul>
    <li id="tab_A" style="display: none" class="hiddenDivs">
        @{Html.RenderPartial("~/Views/Claims/FroiReport/_Insurer.cshtml");}
    </li>

    <li id="tab_B" style="display: none" class="hiddenDivs">
        @{Html.RenderPartial("~/Views/Claims/FroiReport/_Insurer.cshtml");}
    </li>
</ul>

Displaying div using script on click event. 在点击事件中使用脚本显示div。

 self.ShowHideDiv = function (tabToShow) {
        console.log(tabToShow);
        $('.hiddenDivs').html('');
        $('#' + tabToShow).show();
    };  

Now, the problem is that the UI using this code is working fine for 3-4 views but the design is breaking for the remaining views possibly because there are too many divs which are being hidden (I am not sure here). 现在的问题是,使用此代码的UI可以在3-4个视图中正常工作,但是对于其余视图,设计可能会中断,这可能是因为有太多被隐藏的div(我不确定此处)。

So, I was looking into other options where I will load the specific view at run-time only. 因此,我正在研究其他选项,这些选项仅在运行时加载特定视图。 When user clicks on a tab, get the partial view and load it. 当用户单击选项卡时,获取部分视图并加载它。

Hence, I tried something like this: 因此,我尝试了这样的事情:

self.ShowHideDiv = function (tabToShow) {
    $('.hiddenDivs').html('');
    var view = getValueFromDict(dict, tabToShow); //gets the needed view from a dictionary in "~/Views/Products/CoolProducts/_ItemOne.cshtml" format
    $('.hiddenDivs').load('/Claims/ReturnPartialView/?partialViewName=' + view);
};

But this doesn't work since I do not have any Action/Controller associated with these views, I am unable to load the view directly using javascript/jquery. 但这是行不通的,因为我没有与这些视图关联的任何动作/控制器,我无法使用javascript / jquery直接加载视图。

Another option I have tried is creating a controller that returns a partial view. 我尝试过的另一个选项是创建一个返回部分视图的控制器。

public ActionResult ReturnPartialView(string partialViewName)
        {
            return PartialView(partialViewName);
        }

and calling it like this: 并这样称呼它:

self.ShowHideDiv = function (tabToShow) {
    $('.hiddenDivs').html('');
    var view = getValueFromDict(dict, tabToShow);
    $('.hiddenDivs').load('/MyController/ReturnPartialView/?partialViewName=' + view);
}

Now this loads the view that I need but the KnockOut observable associated with the view is coming as null doing this. 现在,这将加载我需要的视图,但与此视图相关联的KnockOut可观察对象将作为null来执行此操作。

I heard that KO templates can be used for my scenario but have not yet tried KO templates to solve this (which I am going to look into next). 我听说可以将KO模板用于我的方案,但尚未尝试使用KO模板来解决此问题(我将在下一步中进行探讨)。 I would like to see if anyone has solution to my problem without using the KO templates. 我想看看是否有人不用我的KO模板就能解决我的问题。

Thanks much for your patience to trying to understand this. 非常感谢您耐心尝试理解这一点。

You can do this with jQuery in two steps.First from your view hit the desired controller action after the dom is ready or when an event is occurred. 您可以分两步使用jQuery进行此操作。首先,从您的视图中,在dom准备就绪或发生事件时击中所需的控制器动作。 I have call controller here after the dom is ready. dom准备好后,我在这里有呼叫控制器。 You can hit action get or post method as you wish. 您可以根据需要点击操作get或post方法。
Here in $.ajax I have used ( async: false ) so that the statement now I am calling has to be completed before the next statement in the function can be executed. 在$ .ajax中,我使用了( async:false ),因此必须先完成我正在调用的语句,然后才能执行函数中的下一条语句。

<script>
    $(document).ready(function () { 
        $.ajax({
            url: '/Controller/ActionNAme',
            type: 'POST',
            async: false,
            data: { ModelField: value},
            success: function (result) {
                $("#your_desired_div_id").html(result);
            }
        });
    });
</script>

Here is the action. 这是动作。 The action return a view model as result to ajax.post function and in the ajax post function your your_desired_div_id content is changed with the partial view's contents. 该操作将视图模型作为结果返回给ajax.post函数,并且在ajax post函数中,your_desired_div_id的内容将随部分视图的内容而变化。

 [HttpPost]
        public ActionResult ActionNAme  (ModelName ModelField)
        {
            var dBList= (from myTable in db.tableModel where myTable .column == ModelField.column  select  myTable).ToList();
                 return PartialView("_PartialView", dBList) 

        }

You should have a controller action which returns the partial view. 您应该具有返回部分视图的控制器操作。

public ActionResult MyPartialView()
    {
        return PartialView("_MyPartialView", new MyPartialViewModel());
    }

You can call this controller method from javascript. 您可以从javascript调用此控制器方法。 Make sure the partial view exists in Views folder under the folder which matches your controller name. 确保部分视图存在于与您的控制器名称匹配的文件夹下的“视图”文件夹中。

Hope it helps! 希望能帮助到你!

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

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