Loading a partial view in ASP.NET MVC using javascript

跟風遠走 提交于 2019-12-25 03:45:13

问题


I have about 15 partial views that I need to display based upon user's menu tab selection. 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.

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.

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.

 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).

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.

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.

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). I would like to see if anyone has solution to my problem without using the KO templates.

Thanks much for your patience to trying to understand this.


回答1:


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. I have call controller here after the dom is ready. You can hit action get or post method as you wish.
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.

<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.

 [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) 

        }



回答2:


Same has been explained here..

https://cmatskas.com/update-an-mvc-partial-view-with-ajax/




回答3:


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. Make sure the partial view exists in Views folder under the folder which matches your controller name.

Hope it helps!



来源:https://stackoverflow.com/questions/34528975/loading-a-partial-view-in-asp-net-mvc-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!