Reputation: 198
I want to update my partial View with Ajax, but for some reason, it doesn't work. If I use load method (and comment ajax code), it works. this is my code:
this is my main View:
@model IEnumerable<WebApplicationMVC.Models.Test>
@{
ViewData["Title"] = "Testing";
}
<div id="partial">
@await Html.PartialAsync("Question", Model.ToList()[0])
</div>
<input type="button" id="b" value="next" class="btn btn-default" />
<script>
$("#b").click(function () {
//this code doesn't work
$.ajax({
url: 'Test/Question',
type: 'GET',
contentType: "application/json; charset=utf-8",
data: { id: '@Model.ToList()[1].ID' },
dataType: "json",
success: function (result) {
$("#partial").html(result);
}
});
//this code works
@*$("#partial").load('@Url.Action("Question","Test",new { id=Model.ToList()[1].ID })');*@
});
this is my question action method int Test controller:
public IActionResult Question(int id)
{
return View(Methods.GetTestById(id));
}
what mistake do I have?
Upvotes: 1
Views: 4191
Reputation:
You have specified dataType: "json",
but your method returns a view (html), not JsonResult
so an exception is being thrown.
Either omit the dataType
option (the function will work it out based on the response) or change it to dataType: 'html'
In addition, your can delete the contentType
option. You are making a GET which has no body so its ignored (and if it was a POST, your method would also fail because you have not stringified the data).
Your url should also be /Test/Question
(leading forward slash), and you should always use the @Url.Action()
method to generate the url
Your function should be
$.ajax({
url: '@Url.Action("Question","Test")',
type: 'GET',
data: { id: '@Model.ToList()[1].ID' },
success: function (result) {
$("#partial").html(result);
}
});
Upvotes: 1