Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

asp.net MVC partial view controller action

I'm very new to web app development and I thought I would start with recent technology and so I'm trying to learn asp.net as-well as the MVC framework at once. This is probably a very simple question for you, MVC professionals.

My question is should a partial view have an associated action, and if so, does this action get invoked whenever a normal page uses RenderPartial() on the partial view?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 );
     }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...