I was requested to create a page in asp.net which gets the windows login info from the user, connects to the active directory and them gets the employee info. After this, I have to register the Internal ID, Name and timestamp of when the user access this page.
I was able to do all of this adding a submit button to the web page, calling the method "Add" that I created. However, How can I do it automatically when the page loads?
I really don’t know how to proceed from here this is how it’s working now:
The add page:
@model TrainingReportLogger.Models.AddTrainingReportLogViewModel
<h1> Parabéns!</h1>
<h2>Clique no botão abaixo para concluir o curso</h2>
<form method="post">
<div class="mt-3">
<button type="submit" class="btn btn-primary">Concluir</button>
</div>
</form>
The method is being called: ps: i deleted the "Directoryentry", but it works.
[HttpPost]
public async Task<IActionResult> Add(AddTrainingReportLogViewModel viewModel)
{
var loginName = login.Split('\')[1];
DirectoryEntry dom = new DirectoryEntry;
DirectorySearcher searcher = new DirectorySearcher(dom, "(samAccountName=" + loginName + ")");
SearchResult adUser = searcher.FindOne();
string displayName = adUser.Properties["DisplayName"][0].ToString();
string gid = adUser.Properties["employeeId"][0].ToString();
var trainingreportlog = new TrainingReportLog
{
Name = displayName,//login,//viewModel.Name,
GID = gid,
Timestamped = DateTime.Now.ToString("dddd, dd MMMM yyyy HH:mm:ss")//viewModel.Timestamped
};
await dbContext.TrainingReportLogs.AddAsync(trainingreportlog);
await dbContext.SaveChangesAsync();
return RedirectToAction("List", "TrainingReportLogs");
}
2
Answers
You can create a Ajax post request function to call the C# function in jquery/javascript
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
Then you can call this function in the javascript onload/jquery document ready function, which automatically executes on page load:
https://learn.jquery.com/using-jquery-core/document-ready/
Each website has
onload
event, according to your description, you just need to use js code to click the submit button, so tha you could skip the step which requiring users to click the button. Then we can give an id to the button like this<button type="submit" id="addBtn" class="btn btn-primary">Concluir</button>
, then add codes like below at the bottom of the add page.HTML and scripts will be run from the top to the bottom. After the html is rendered, then the script will be executed, and the button would be click by js.