'how to preform jquery http post req in asp.net mvc
I want to post a single string to my controller from the view. The string is the name of a website.
on the view, the the users clicks a website's name , I want to render info based on the clicked website name.
my view(note all websites render 100%)
<h1>My Websites</h1>
@{
foreach (var website in Model.websites)
{
<table>
<tr>
<td> <a class="websiteLink" href="">@website </a> </td>
</tr>
</table>
}
}
MVC action
[HttpPost]
public ActionResult getWebsiteName(string webiste)
{
//return partial view here
return RedirectToAction("WebsiteOptions", "Home");
}
js:
document.querySelectorAll('.websiteLink').forEach(item => {
item.addEventListener('click', event => {
var websiteName = item.innerHTML;
$.post("/Home/getWebsiteName", { WebsiteName: websiteName }, function (data) {
console.log(data);
});
//alert(WebsiteName);
});
});
when I do the alert function to test it works fine, the correct website name is shown when clicked, I just want to post the clicked website name to my controller but it's not working :( nothing happens in the action yet because it does not work.. I've set e breakpoint there to test if the parameter is correct
Solution 1:[1]
the below solved my problem
document.querySelectorAll('.websiteLink').forEach(item => {
item.addEventListener('click', event => {
//storing clicked website name
var websiteName = item.innerHTML;
item.style.textDecoration = "underline";
$.ajax({
type: "POST",
url: "@Url.Action("getWebsiteName")",
dataType: "json",
data: { WebsiteName: websiteName },
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
});
Solution 2:[2]
your request is supposed to look like this:
document.querySelectorAll('.websiteLink').forEach(item => {
item.addEventListener('click', event => {
var websiteName = item.innerHTML;
$.post("/Home/getWebsiteName?website=" + websiteName, function (data) {
console.log(data);
});
//alert(WebsiteName);
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kyle |
| Solution 2 | big boy |
