2016年1月30日 星期六

[ASP.NET MVC] Render PartialView by JS (angularJS | Vue | jquery)

 .NET   MVC    PartialView

Introduction


The PartialView doesn’t have a Controller and Actions in default.
But if we would like to pass the view model through its own Controller, we can use Html.Action to replace Html.Partial .


Updated!
We can use ajax way to render the PartialView to approve UX.



Environment

MVC 5
Vue.js 2.4.2
angularJS 1.4.2
jquery 3.X


Implement back-end


View

<body>
    @RenderBody()
    @Html.Action("Footer","PartialView",new { area=string.Empty})
    @*@Html.Partial("_FooterPartial")*@
</body>

The parameters of Html.Action shows that we are going to run the Footer Action on PartialViewController.

Controller

public ActionResult Footer()
{
      //Create a new view model
      var viewModel = new VmFooter();
      return PartialView("~/Views/Shared/_FooterPartial.cshtml", viewModel);
}





Implement front-end



We will ajax the PartialView’s html and render it.


angularJS

HTML

<div id="partialview">
</div>


JS

var getUrl = "…";
$http.get(getUrl).success(function (data) {
            $scope.isRenderDone = true;
            var $el = $(data).appendTo('#partialview');
            $compile($el)($scope);

        }).error(function (data, status, headers, config) {
});
}



jquery


HTML

<div id="partialview">
</div>


JS

$.ajax({
        dataType: "html",
        url: getPartialViewUrl,
        success: function (data) {
            $("#partialview").html("");
            $("#partialview").append(data);
        }   
})



Vue.js (2.X)

HTML

<div :is="compiledDtl">
</div>


JS

var vm = this;

axios.get(uri).then(function (response) {
    vm.compiledDtl = Vue.compile(response.data);
})




沒有留言:

張貼留言