The goal is to load the partial view without refreshing the entire page, just the partial view iteself, and when I do that, I want the model that I’m passing into the view the int to increment.
But when I try to load the view by pressing my button it says..
XML Parsing Error: no root element found Location in Console
It’s interesting because in the console it also outputs
<h1>Hello from _Items partial view. + 1</h1>
This is my index.cshtml
<button class="btn btn-primary" onclick="LoadInfo()">Load</button>
<div class="text-center">
</div>
<script>
function LoadInfo() {
$.ajax({
url: "Home/LoadView",
type: 'GET',
success: function (response) {
console.log("Did it get called is the question..");
console.log("Response: " + response);
$(".text-center").load(response);
}
});
}
</script>
And the partial view
@model int
<h1>Hello from _Items partial view. + @Model</h1>
As well as the controller
int i = 0;
[HttpGet]
public IActionResult LoadView()
{
i++;
return PartialView("_Items", i);
}
2
Answers
Use following:
The load() method loads data from a server i.e. if you want to load data from any file then you can use load(). But as you are getting data from partial view and partial view returns HTML document which you need to add into selected div. so, whenever you’ll use partial view then try to avoid using load().
As @Rutuja said, you need to change
.load() to .html()
method to solve your current issue.Because every time you click the
Load
button, you are re-entering theLoadView
method of the entire controller, soi
will be re-assigned the default value of 0, instead of superimposing based on the previous data.To achieve the number of clicks, I suggest that you pass the i variable value from js to LoadView, as shown below:
Controller:
Here is the result: