I am having trouble returning JSON from a controller in response to an AJAX form post. The form posts, but after the response, it just replaces the current view's markup with the JSON string written to the page: "{"test":"test1","test2":"test2","test3":"test3"}"
I am using .NET Core 3.1, and I have jQuery JavaScript Library v3.3.1 and jquery.validate.unobtrusive v3.2.11 installed and referenced in my layout page.
I am transitioning to Asp.Net Core MVC from Asp.Net MVC 5. In the past I would use Ajax.Beginform like this, and I thought I would be able to do something similar in Core MVC. I have scoured a few different tutorials on this topic, but I am not sure where I am going wrong. I did add the, "AddMvc()" references in the Startup.cs but results in the same thing happening.
What I am trying to accomplish: I have a Modal window that pops up to upload a file. I am looking for feedback that it uploaded properly to alert the user. So I figure I would respond with JSON using Ajax to do so.
Form:
<form asp-controller="Home" asp-action="Upload" data-ajax="true" data-ajax-begin="onBegin"
data-ajax-complete="onComplete" data-ajax-failure="onFailure">
Functions (Basic setup for testing):
function onFailure(result) {
alert("onFailure ");
};
function onComplete(result) {
alert("onComplete " + result.test + " " + result.test2 + " " + result.test3);
};
function onSuccess(result) {
alert("onSuccess " + result.test + " " + result.test2 + " " + result.test3);
};
function onBegin(result) {
alert("onBegin ");
};
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Upload(UploadViewModel model)
{
//File handling logic..
return Json(new
{
test = "test1",
test2 = "test2",
test3 = "test3"
});
}
