Wednesday, April 8, 2015

Multiple partial view

http://www.codeproject.com/Tips/712187/Returning-More-Views-in-an-ASP-NET-MVC-Action

public ActionResult Sample()
{
 MyClass cla = new MyClass { Student = new Student { ID = 1, Name = "Student" }, Teacher = new Teacher { ID=1, Name="Teacher" } };
            return Json(cla,JsonRequestBehavior.AllowGet);
        }


@Ajax.ActionLink("Click Me", "Sample", new AjaxOptions { HttpMethod="Get", OnComplete="_Complete"})
<script type="text/javascript">
    function _Complete(data) {
        var JsonObj = $.parseJSON(data.responseText);
        $("#span1").html(JsonObj.Student.Name);
        $("#span2").html(JsonObj.Teacher.Name);
    }
</script>
<br />
<span id="span1"></span>
<br />
<span id="span2"></span>

http://stackoverflow.com/questions/6342951/how-to-refresh-multiple-partialview-on-click-of-ajax-actionlink

Keep it simple - use jQuery - then you have total control:
$(function() {
   $('#somelink').click(function(e) {
      e.preventDefault();

      $.get('/controller/action1', function(data) {
         $('#up').html(data);
      });

      $.get('/controller/action2', function(data) {
         $('#down').html(data);
      });
   });
});
However, since you're updating both panels, I would suggest wrapping those two middle panels in a partial view of it's own - then serve that via a single action method - that way you only need 1 ajax call.
Edit
As @FelixM mentions, you should use Url.Action or Url.RouteUrl to generate the URL for the AJAX call, so if your routes change then your JS need not, e.g:
.get('@Url.Action('Controller', 'Action1')', function(data)
or
.get('@Url.RouteUrl('SomeNamedRoute')', function(data)
If your putting this script in an external file then you'll need to use a technique to set the url in the main view, then read from the external variable.
Such techniques include a JavaScript variable, hidden field, passing URL to function as parameter, etc.

No comments:

Post a Comment