Reputation: 68
I can read data and display it on aurelia-SPA like this:
In my ASP.NET controller I have:
[HttpGet("[action]")]
public IEnumerable<Team> Teams()
{
var Teams = _teamRepository.GetAllTeams().OrderBy(p => p.Name);
return Teams;
}
On aurelia-page typescript file I can then read data like this:
@inject(HttpClient)
export class Fetchdata {
public Teams: Teams[] | undefined;
constructor(http: HttpClient) {
http.fetch('api/SampleData/Teams')
.then(result => result.json() as Promise<Teams[]>)
.then(data => {
this.Teams = data;
});
}
And then in aurelia-page html file I can show the data like this:
<template>
<h1>Teams in database</h1>
<p if.bind="!Teams"><em>Loading...</em></p>
<table if.bind="Teams" class="table">
<thead>
<tr>
<th>TeamName</th>
</tr>
</thead>
<tbody>
<tr repeat.for="team of Teams">
<td>${ team.name }</td>
</tr>
</tbody>
</table>
</template>
This works fine. Now I cannot find any example on how to create a simple form and post data from it to the ASP.NET controller. For example If my aurelia html would contain a form like this:
<form role="form" submit.delegate="postdata()">
<label for="name">Teamn Name</label>
<input type="text" value.bind="name" placeholder="Name">
<label for="teamurl">TeamUrl</label>
<input type="text" value.bind="teamurl" placeholder="Teamurl">
<button type="submit">Add Team to DB</button>
</form>
Upvotes: 1
Views: 211
Reputation: 655
In your view model which corresponds to the view with the form you have in your question - you would need to implement your postdata()
method. Given that the view model has HttpClient
injected and assigned to the property called http
and properties called name
and teamurl
declared on this same view model and there is a property called postPath
value of which is the url for your post endpoint - postdata
method would look something like this:
public async postdata(): Promise<bool> {
if (!this.name || !this.teamurl) {
return; // no valid data. abort.
}
// given that there is a type called Team and it has a constructor which
// takes corresponding parameters - init up a new instance of Team with
// current name and teamurl values
let payload = new Team(this.name, this.teamurl);
try {
await this.http.fetch(postPath, {
method: "post",
body: JSON.stringify(payload),
}).then(response => response.json());
// return true if no error, there might be a need for more complicated logic here
// depending on what your post endpoint returns
return true;
} catch(e: Exception) {
console.log("Error: ", e.Message); // handle the error logging however you need.
return false;
}
}
Upvotes: 1