In this article I will try to explain how to load a partial from jquery using controller method in MVC.
Some times it needs to load a partial from jquery. In this article I have tried to explain this with the help of a simple example. Let's see this step by step.
In my example I will create a controller, a view, a partial view and will put some jquery code to load my partial view. In jquery I am using two methods - $.aajx() which is used from asynchronous task and $.load() method which is especially made for this purpose. You can any of these method. Let's start with controller.
I am creating a controller and as usual putting its name as Example. You can put your name. Here is the code for same.
public ActionResult Index()
{
return View();
}
[HttpPost]
public PartialViewResult CallPartial(int value)
{
return PartialView("_InnerPartial", value);
}
Let's create a simple view. I am using default Index view for this.
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="divPartial"></div>
Now let's create a simple partial view and name it as _InnerPartial. Below is the code for the same.
@model int
@{
<h1>This is a partial view</h1>
<h3>You passed value=@Model</h3>
}
Now let's add script to load the partial view. I have put this code on Index view. Here is the code.
<script>
$(document).ready(function () {
//you can any method to load your partial.
AsyncAjaxCallback();
//AsyncCallback();
});
function AsyncCallback() {
var ctrl = $("#divPartial");
var url = "/Example/CallPartial";
if (url && url.length > 0) {
ctrl.load(url, { value: 45 });
}
}
function AsyncAjaxCallback() {
$.ajax({
type:"POST",
url: "/Example/CallPartial",
data: { value: 78 },
success:function(result)
{
$("#divPartial").html(result);
}
});
}
</script>
Hope this can help you. Use it in your code and enjoy.