I am currently working on an MVC project that involves filling out forms with user information. Each recorded entry is given a unique Id that is associated with all the details submitted in the form.
My next task is to create a page for editing these forms, which requires passing the id through the URL and assigning it to Viewbag.Id. I want to use this Id in an ajax call to retrieve the remaining information from the web API and populate the fields with the existing data. However, as I am still learning about ajax, I am unsure of how to accomplish this effectively. Below is the relevant code snippet:
Controller Code:
@Route("EditUser/{id}")]
@CustomAuthorize(Roles = UserRole.Any)
public ActionResult EditUserDetails(int id)
{
var userDetails = _slg_Entity.NewUser.FirstOrDefault(z => z.Id == id);
ViewBag.Id = userDetails.Id;
return View("~/Views/Request/EditUser.cshtml");
}
This is the jquery/ajax call I am attempting to implement:
$.ajax({
type: "GET",
url: "@Url.Action("UserDetails", "Api/Request")",
data: {
Id: "@ViewBag.Id" // ID passed to the API controller
}
}).done(function (data) {
$(".firstname").val(variable); // Assigning data from API to field value
}).fail(function (error) {
displayError(error);
});
API Controller Code:
@Route("UserDetails")]
@HttpGet
@CustomApiAuthorize(Roles = UserRole.HR)
public async Task<IHttpActionResult> GetUserDetails([FromUri] NewUserDetails existingUser)
{
var details = await _slg_Entity.NewUser.FirstOrDefaultAsync(z => z.Id == existingUser.Id);
existingUser.FirstName = details.FirstName;
return Ok(details);
}
I'm not sure if I'm on the right track, so any tips or feedback would be greatly appreciated! Thank you.