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);
});
Related
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.
I have been trying to send a list model to controller using ajax but it seems it is not working at all
Model
public string MyModel {
public string myfieldName {get;set;}
}
controller
public JsonResult Create(List<myModel> list)
{
return Json("Success");
}
post request
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC' }, { myfieldName: 'DEF' }];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: JSON.stringify({ list }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
so when I send this through, I check the browser and I can see that the request payload is sent with json object list
However when I go to controller the list is not binding it at all, so I check the http.context to check the request payload there and it all empty.
on the other hand when I change the controller like below
sending request with only model
public JsonResult Create(myModel data)
{
return Json("Success");
}
and change the js with below
$("body").on("click", "#btnSave", function () {
var data ={};
data.myfieldName= "test";
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Project/Create",
data: data,
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
the only difference here is that I don't send as json, so my question what is the is the difference between sending model vs a list of model using ajax
and what can I change to get the controller to bind the data or accept a list of model data
noting i'm using .Net core 2.0
Thank you
I usually use this method to send my Model as a List to my Controller method. I will try to show you regarding your scenario, how you can do this:
AJAX:
$("body").on("click", "#btnSave", function () {
var list= new Array();
list = [{ myfieldName: 'ABC'}, { myfieldName: 'DEF'}];
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "#Url.Action("Create","Project")",
data:{"json": JSON.stringify(list)},
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
}
});
});
And you can receive your Model like this in your Create method:
Make sure to import the System.Web.Script.Serialization namespace:
using System.Web.Script.Serialization
[HttpPost]
public JsonResult Create(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
List<string> myfieldName=new List<string>();
//Access your array now
foreach (var item in jsondata)
{
myfieldName.Add(item["myfieldName"]);
}
//Do something with the list here
return Json("Success");
}
Hope this helps you out.
Another method would be to utilize unobtrusive AJAX. All you would need is to install Microsoft jQuery unobtrusive AJAX from your Nuget Package Manager.
Then, in your view, call the following:
#{using (Ajax.BeginForm("Create", "ControllerName", null, new AjaxOptions()
{
HttpMethod = "POST",
// ...
}
}))
{
// Html code goes here
}
And also make sure that you include this at the bottom of your view:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
Then, you can have a normal ActionResult setup (instead of JsonResult) for your controller and accept an argument of List list.
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
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.
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!