MVC 5 generate form data with AJAX - javascript

I need a way to generate a new unique id for a user when a person focuses out of a textbox. I am using MVC 5 for this application. Here is my controller, everything in the controller has been unit tested and it does return the string value that I need.
Controller. I was able to visit that URL, and I did download a JSON file with the correct data.
public ActionResult GetNewId()
{
string newId = utils.newEmployeeId();
return Json(new {eId = newId}, JsonRequestBehavior.AllowGet);
}
Javascript, JQuery call to that controller. I do not know how to properly reference the ActionResult. I keep getting undefined errors on eId.
$(function () {
$('#employeeId').focusout(function () {
if($("#employeeId").val() === "NP")
$.ajax({
type: 'GET',
url: '#Html.ActionLink("GetNewId", "Employees")',
data: { 'eId': eId },
dataType: 'json',
success: function (response) {
$("#employeeId").val(eId);
},
error: function (response) {
alert(response);
}
});
});
});

The problem is with yout ajax request:
1.you need to change the url in the reuqest but it like this
{{yourcontroller}/GetNewId}
2.remove the "data: { 'eId': eId }" you dont need it, youre not posting anything to the server.
change your $("#employeeId").val(eId); to
$("#employeeId").val(response.eId);
this will 100% work

Related

Ajax & Laravel 8: select term + onchange event = show cost in input type number

I'm trying to dynamically change <input type="number" name="SLACost" readonly> based on <select name="SLATerm"> option
A table (in DB) that contains:
SLATerms.
SLACost.
SLADeduction
that should be fetched in the "Add new KPI Invoice" form.
I created a function in the controller to fetch the data as json:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::all();
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
created a url for ajax to fetch in the web.php as Route::get('kpi/fetch/sla', 'fetchSLA')->name('kpi.fetchSLA'); // The API for fetching SLA as json
Then went ahead and created the ajax request GET
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
// console.log(response.SLATermData);
$("select[name='SLATerm']").change(function() {
$("input[name='SLACost']").val(response.SLATermData);
});
}
});
}
Obviously, SLATermData will fetch the entire data as json and print it in the SLACost input, it shows as [onject object object]
I tried to do this:
$("select[name='SLATerm']").change(function() {
$("input[name='SLACost']").val(response.SLATermData.SLACost);
});
I thought that adding SLACost after response.SLATermData will do the trick.
What's missing here?
So I made an ajax request to both SLATerm and SLACost and looped through the requested data. Then I made an if statement within the loop to change the SLACost based on the SLATerm selected.
function fetchSLA() {
$.ajax({
type: 'GET',
url: "/management/kpi/fetch/sla",
dataType: 'json',
success: function (response) {
$.each(response.SLATermData, function (key, value) {
$("select[name='SLATerm']").change(function() {
if ( $("select[name='SLATerm']").val() == value.SLATerm ) {
$("input[name='SLACost']").val(value.SLACost);
}
});
});
}
});
}
And here is the Laravel controller for the API:
/**
** KPI API
**/
public function fetchSLA()
{
$kpiTerms = KPITerms::get(['SLATerm' => 'SLATerm', 'SLACost' => 'SLACost']);
return response()->json([
'SLATermData' => $kpiTerms, // SLATermData is the name that will be used in Ajax.
]);
}
Now That I got it working, I'm trying to figure out how to clean the code.
As CBroe mentioned in the comments:
you should rather change your API - requesting all the data over and
over again
Which I am trying to do.

Populate text fields with ajax call

I have an MVC project for filling out forms with user information. Once recorded it gets a unique Id associated with all the details in the form.
I then have a page to edit the form if needed which takes the id into to the url and assigns the Id to Viewbag.Id. I'm trying to use the Id in an ajax call to then pull the rest of the information from the web api and populate the fields with the details that have already been filled out. My problem is that I'm still learning ajax and not 100% on how to accomplish this. Below is what I think is relevant.
My Controller
[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");
}
I'm trying to do something like the following:
$.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); <--- assign the data from api to field value
}).fail(function (error) {
displayError(error);
});
Api controller:
[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);
}
Not sure if I'm close or in the ball park, so any advice is welcome!
Thanks.
So the data was getting passed through fine. I just figured out I was calling it incorrectly.
instead of just passing the variable I created in my controller, I forget to include the data prefix.
$.ajax({
type: "GET",
url: "#Url.Action("UserDetails", "Api/Request")",
data: {
Id: "#ViewBag.Id"
}
}).done(function (data) {
$(".firstname").val(data.variable);
}).fail(function (error) {
displayError(error);
});

Upload Attachment and some additional parameters to MVC Controller

I have a MVC Controller with the following signature:-
[HttpPost]
public async Task<JsonResult> SaveBrochureAsAttachment(Guid listingId, HttpPostedFileWrapper attachmentFile)
{
///some logic
}
How do I make an ajax call and send the file attachment and additional listingId parameter. Currently I am only able to send the attachment like this:-
var uploadFile = function () {
if ($('#attachmentFile').val()) {
}
else {
alert('No File Uploaded');
return;
}
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
url: '/Listing/SaveBrochureAsAttachment',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert('File Uploaded');
},
error: function (jqXHR, textStatus, errorThrown) {
$("#FileUpload").replaceWith($("#FileUpload").val('').clone(true));
alert('File Uploaded Error');
},
cache: false,
contentType: false,
processData: false
});
return false;
}
Currently as you folks can see I am only able to send the attachment. How do I also send the Guid listingId to match the controller signature.
Try adding another formdata parameter:
formData.append("listingId", guidValue);
Provided you have the guid value accessible. You can use this to generate one from the client. Or create one from the server:
var guidValue = '#Guid.NewGuid()';
one approach would be to your controller accept viewmodel (a class) which contains different property you need. and use formdata.append required stuff to post to the server.
On Server side; you will need to use modelbinder so that you will get required stuff populated.
Refernce for modelbinder : https://www.dotnetcurry.com/aspnet-mvc/1261/custom-model-binder-aspnet-mvc
you can get more on google. :)

MVC Web Api Get Data with Ajax

I'm trying to get all my posts from the database to be displayed with the help of ajax or getjson but can't get it to work. Using mvc web api and I have a view where I want to display it. There is a method working called post so nothing wrong with my routing etc.
Code for my views js-script, I want to display all posts with the help of my mvc api controller and ajax in a div called #userMessage.
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/GetPosts" ,
//data: (?)
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
my controller method to get all the posts
// GET: api/Posts
public IEnumerable<Post> GetPosts()
{
//querystring is made to get the recieverID, it's also reachable in the view. //("#RecieverID")
string querystring = HttpContext.Current.Request.QueryString["Username"];
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(querystring);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
my PostRepository.GetSpecifiedUserPosts method in my repository
public List<Post> GetSpecificUserPosts(int user)
{
using (var context = new DejtingEntities())
{
var result = context.Posts
.Where(x => x.RecieverID == user)
.OrderByDescending(x => x.Date)
.ToList();
return result;
}
Try this
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/Posts" ,
data: {
username: recieverID
},
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
and in code behind,
public IEnumerable<Post> GetPosts(string username)
{
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(username);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
You use wrong url. Try send ajax request to '/api/Posts'.
Also you can add routing attribute to the action [Route('/api/Posts/GetPosts')] and send request to '/api/Posts/GetPosts'.
See Calling the Web API with Javascript and jQuery and Routing in ASP.NET Web API.

MVC How to pass data from view to model using Ajax

Hello I'm posted a question asking what to use to send information from a view to a model. I realize that the info needs to be send to the controller and then to my model. I got some code that send info from my view to my controller:
Here is the Ajax:
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content fom the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
alert(data);
},
error: function (e) { alert(e); }
})
});
});
An this is the code in my controller:
[HttpPost]
public ActionResult processCommand(string cmd)
{
return Json(cmd);
}
I've tested it and send my input in json. However my problem is, I don't know how to take the string out of that and send it to my model. Please any help would be appreciated.
As stated in the comments to your question, the terminology you use is a little confusing, but if understood your question correctly, you want an action on your controller on the server to accept a 'command' and work with it.
The following post can be made, in order for the ajax post to successfully hit the action :
$('#cmdSend').click(function () {
var cmdInput = document.getElementById('cmdInput').value;
$.ajax({
url: 'terminal/sendInfo',
type: 'POST',
data: {cmd : cmdInput},
dataType: 'json',
success: function (data) {
//What you want to do with the returned string with data.cmd
}
});
});
The controller action would be like the following :
public class TerminalController : Controller
{
[HttpPost]
public JsonResult sendInfo(string cmd)
{
//Do what you want to do with 'cmd' here.
return Json(new { cmd = "Whatever you want to send" }, JsonRequestBehavior.AllowGet);
}
}
Hope this helps!

Categories