Rendering Partial Views Using Ajax

Rendering Partial Views using ajax

If you want to load the page and then load the partial view via ajax you could create an ActionMethod that does something like:

public ActionResult Create()
{
var model = new MyModel();

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

and then in your page do something like:

$(function(){

$(document).ajaxStart(function () {
//show a progress modal of your choosing
showProgressModal('loading');
});
$(document).ajaxStop(function () {
//hide it
hideProgressModal();
});

$.ajax({
url: '/controller/create',
dataType: 'html',
success: function(data) {
$('#myPartialContainer').html(data);
}
});
});

Rendering a partial view with ajax

Given the reported error message, you need to alter your ajax call. By setting "data" parameter to "json" you're telling ajax to expect JSON-formatted data back in the response, but a partial view is HTML, so change your ajax call to reflect this:

$.ajax({
type: "POST",
url: '@Url.Action("getRolesByYear", "WorkRoles")/' + year,
dataType: "html", //set the correct data type for the response
success: successFunc,
error: errorFunc
});

As an aside, you can improve your error handling on the client side quite straightforwardly by changing errorFunc to something like this, using the parameters that are provided to the callback by $.ajax:

function errorFunc(jQXHR, textStatus, errorThrown) {
alert("An error occurred while trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
}

For less instrusive reporting and/or easier debugging, you could change the alert to console.log. To get more detail you could also log the entire jQXHR object:

console.log(JSON.stringify(jQXHR));

Render partial view with JQuery / AJAX

Without seeing the error you mentioned I do see one issue with your code, the content type on your ajax call is incorrect it should be:

$.ajax({
url: '@Url.Action("GetMessageTypeView", "EmailMessages")',
type: "POST",
contentType: "text/html; charset=utf-8",
success: function (data) {
$('#target').html(data);
}
});

jquery is expecting json to be returned from the server but when it gets the html of the partial view it doesn't know what to do with it. I've had this problem recently and I didn't even get an error, it just didn't do anything.

Problem with rendering partial view using Ajax

As you are returning modal whole html as partial view, you will need to call the modal("show") on the modal div element to show it:

success: function (t) {
$("#modalBody").html(t);
$("#product-pop-up").modal("show");
},

The approach i normally do is put the modal on the parent view i.e. the main view not partial view :

<div class="modal fade" id="modal-id" role="dialog" aria-labelledby="" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" class="la la-remove"></span>
</button>
</div>
<div class="modal-body" id="modal-body-id">
</div>

</div>
</div>
</div>

and in ajax call success push the html from partial view as content of popup body and call .modal("show") :

 success: function (t) {
$("#modal-body-id").html(t);
$("#modal-id").modal("show");
},

or we can put the following attributes on the button, in that case the popup should be on the page already which means it should be already on the main view:

<button type="button" class="btn btn-primary" 
data-toggle="modal" data-target="#modal-body-id">

Laravel: rendering partial views with AJAX requests

You are getting confused.

Laravel is already doing the rendering of the partial. You are calling View::make() and returning the rendered view to $html.

Then you are passing the rendered view to jQuery, which is simply displaying the data given to it - its not doing any of the calculations itself.

ASP.NET MVC rendering partial view with jQuery ajax

All load does is return HTML from a server, so why not just append to a temporary div and then get the HTML from it on success?

var $dummy = $("<div>");
$dummy.load("MyController/Details", function(response, status, xhr) {
var $container = appendContainer();
if (status != "success") {
$container.html('an error has occured');
}
else
{
$container.html($dummy.html());
}
$dummy.remove();
});

UPDATE:

If you're expecting an exception then you should handle it. If you're basically allowing the error to occur just to get status != "success" then that's a serious code smell. You should catch the error and return a different PartialView.

public ActionResult Details(int id)
{
try
{
DetailsViewModel model =
ModelBuilder.GetDetailsViewModel(id, _repository);
return PartialView("Details", model);
}
catch (SomeException ex)
{
return PartialView("Error", ex.Message);
}
}

Then you're guaranteed to always get a valid HTML response and if you don't, then your basic error an error occured will come into play.

Rendering Partial Views using AJAX

To make things simpler:

  1. Create an ajax action link for each of the menu link.
  2. Set the UpdateTargetId as the id of div where you want to show your partial view.

Rendering partial view inside a view using AJAX

Posting this because it's not an intuitive fix. Apparently there are issues with MVC 4 and jQuery 1.9.1 so to get this to work I had to change my reference to jQuery 1.7.1

Render partial with ajax and route url

You already have a partial view defined for your [Route("Profile/Skills")].

To accomplish what you want you need to do the following:

Define a regular view for the same route

This view will contain a reference to your partial so the partial is rendered within the larger HTML of the full view (when the route is called directly).

Modify Controller Action to check for Ajax

Once you have a regular view and the partial view then you can modify your controller action to conditionally decide whether to:

  • renderpartial (if the caller is Ajax)
  • or render the full view (if it is not an ajax call)

IsAjaxRequest() method

In past versions of ASP.NET MVC there was a method on the Request object called IsAjaxRequest(). When this method is available your controller action code could be as simple as:

[Route("Profile/Skills")]
public IActionResult Skills()
{
if (Request.IsAjaxRequest())
return PartialView("Skills");
else
return View();
}

ASP.NET Core is missing IsAjaxRequest() method

Unfortunately it seems that this method was overlooked in ASP.NET Core (as best as as I tell at the present time). But it also seems that the underlying code was simple enough that many people have managed to duplicate its behavior without much trouble.

If Request.IsAjaxRequest() is not available to you because of ASP.NET core you should be able to duplicate its behavior in your controller action something like this:

[Route("Profile/Skills")]
public IActionResult Skills()
{
bool isAjaxCall = Context.Request.Headers["x-requested-with"]=="XMLHttpRequest";
if (isAjaxCall)
return PartialView("Skills");
else
return View();
}

A more formalized and reusable approach to the dealing with missing IsAjaxRequest() method is described in this post



Related Topics



Leave a reply



Submit