I have this code for form method in ajax
$.ajax({
type: "GET",
url: "/MainPage/GetAllRecords",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
$.each(data, function (key, value) {
$("#loadNotes").append(
'<form method="GET">' +
'<div class="container py-3 px-4" style = "background-color: #fff;position:relative; height: 8rem; border: #80808012 solid 1px; /* margin-top: 1rem; */ box-shadow: blue; margin-bottom: 7px; overflow: hidden; text-overflow: ellipsis; /* overflow-wrap: break-word; */ ">' +
'<a class="stretched-link" asp-controller="MainPage" asp-action="ShowRecord" asp-route-id="' + value.id + '"style = "color: #6d1cccbf; font-weight: 500; text-decoration:underline;" type="submit">' + value.title + '</a>' +
'<p style="color: #5b5454;font-size: 11pt;height: 3rem; white-space:unset" class="text-break text-truncate">' + value.description + '</p>' +
'</div>' +
'</form>'
) ;
});
},
error: function (response) {
alert(response);
}
});
I already tried to put the form method and other elements under cshtml file and from there it works, it is calling the controller and view but not from ajax.
what am I missing? Please help thank you
4
Answers
the type property you passed as GET should be method I suppose.
The remaining code seems ok. Have you checked your browser console for errors ?
Maybe store the html "form tag" in a variable first then use .html() to append the forms to #loadNotes
And make sure add (document) after your ‘#loadNotes’ to absolutely find the element in the document. $("#loadNotes",
document
)Also success: function and error: function is kinda old. try .done and .fail
Old Method of Ajax.
New Method of Ajax
EDIT: Change this part to
< button
From this
To this
and add action on this
use Backtick “
Here is a whole working demo:
Model:
View:
Controller:
Note:
Tag Helpers are interpreted. In other words, Razor must see them as actual tags in order to replace them. Here, it’s just a JS string, and Razor will not mess with that. So it will not generate the href by js.
You need to set the href value manually. Change the js to: