asp.net MVC partial view controller action

跟風遠走 提交于 2019-11-26 18:19:37

While you can have an action that returns a partial view, you don't need an action to render a partial view. RenderPartial takes the partial view and renders it, using the given model and view data if supplied, into the current (parent) view.

You might want an action that returns a partial view if you are using AJAX to load/reload part of a page. In that case, returning the full view is not desired since you only want to reload part of the page. In this case you can have the action just return the partial view that corresponds to that section of the page.

Standard mechanism

Making use of partial view within a normal view (no action needed)

...some html...
<% Html.RenderPartial( "Partial", Model.PartialModel ); %>
...more html..

Ajax mechanism

Reloading part of a page via AJAX (note partial is rendered inline in initial page load)

...some html...
<div id="partial">
<% Html.RenderPartial( "Partial", Model.PartialModel ); %>
</div>
...more html...

<script type="text/javascript">
   $(function() {
       $('#someButton').click( function() {
           $.ajax({
              url: '/controller/action',
              data: ...some data for action...,
              dataType: 'html',
              success: function(data) {
                 $('#partial').html(data);
              },
              ...
           });
       });
   });
</script>

Controller for AJAX

public ActionResult Action(...)
{
     var model = ...

     ...

     if (Request.IsAjaxRequest())
     {
          return PartialView( "Partial", model.PartialModel );
     }
     else
     {
          return View( model );
     }
}

The accepted answer is completely correct, but I want to add that you can load your partial view using jQuery load. Less configuration needed, if you don't want to consider concurrency.

$("#Your-Container").load("/controller/action/id");

The answer is no. But sometimes you need some controller action behind a partial view. Then you can create an actionMethod wich returns a partial view. This actionMethod can be called within another view:

@Html.Action("StockWarningsPartial", "Stores")

The actionmethod can look like:

public ActionResult StockWarningsPartial()
{
      ....              
      return View("StockWarningsPartial", warnings);

}

and the view 'StockWarningsPartial.cshtml' starts with:

@{
    Layout = null;
}

to make it not render your surrounding layout again.

I was able to achieve something similar with this logic.

Within the .cshtml

@Html.Action("ActionMethodName", "ControllerName");

Within the controller

[Route("some-action")]
public ActionResult ActionMethodName()
{
    var someModel = new SomeModel();
    ...
    return PartialView("SomeView.cshtml", someModel);
}

And that's it.

If you need to pass values from the .cshtml to the action method then that is possible to.

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