I am using Visual Studio 2022, .Net 6, ASP.Net Core and SQL Server. I am very new to all of this and I'm not sure if what I am trying to do is possible.
I have two buttons that invoke a javascript function and pass a number:
<div id=sidebar>
<input type="button" onclick="DisplayData('1')" value="World1"><br>
<input type="button" onclick="DisplayData('2')" value="World2">
</div>
I want the function to treat this number as an Id of an item from a connected database. Then I want to display the Name property of that database item in a div.
<script>
function DisplayData(id){
document.getElementById('name').innerHTML = //What do I put here;
}
</script>
<div id=main>
<p id="name"></p>
</div>
Is there something I can do in javascript or am I on a completely wrong track?
CodePudding user response:
I think you are missing the step to read the entity from your DB. Your front-end JS code should send an AJAX call to your .net core backend to fetch that entity from the DB with seletec ID. And then you can display whatever property from the returned data.
CodePudding user response:
You can use ajax to pass id to action,and action return related name.Then change innerHtml with the related name in js.Here is a demo:
js:
function DisplayData(id) {
$.ajax({
url: "GetName",
data: { id:id},
type: "POST",
success: function (name) {
document.getElementById('name').innerHTML = name;
}
})
}
action:
public JsonResult GetName(int id)
{
string name = //get name from database with the id
return new JsonResult(name);
}
