I am using web api to insert update read delete data from database using angularjs ajax but when i update my data i get error.
My WEB API code for Update:
[Route("api/UpdateAdmin")]
[HttpPost]
public bool UpdateAdmin(Admin admin)
{
using (FirstdbEntities ent = new FirstdbEntities())
{
Admin updatedAdmin = (from c in ent.Admins where c.Name == admin.Name select
c).FirstOrDefault(); //here i get the error System.Reflection.TargetException.
updatedAdmin.City = admin.City;
updatedAdmin.Role = admin.Role;
ent.SaveChanges();
}
return true;
}
my angularjs code that is implemented on click of button:
$scope.Update = function (x) {
var admin = $scope.adminlist[x];
var httprequest = $http({
method: 'POST',
url: "api/UpdateAdmin/",
data: JSON.stringify(admin),
dataType: 'json',
headers: { "Content-Type": "application/json" }
})
.then(function (data) {
alert('Data Updated successfully.');
$scope.adminlist.push(data.data);
});
}
my button:
<input type="button" class="bg-danger" value="Update" ng-click="Update(ax)" />
Kindly advice me what to do.Thanks!!
It seems that you can't send admin parameter to server correctly. Thus admin parameter is always null in your UpdateAdmin method. You need to change usage of JSON.stringify.
So this
data: JSON.stringify(admin)
should be as below in AJAX call:
data: JSON.stringify({admin: admin})
And this is not about the problem but, I would add null check too:
using (FirstdbEntities ent = new FirstdbEntities())
{
Admin updatedAdmin = ent.Admins.FirstOrDefault(i=> i.Name == admin.Name);
if(updatedAdmin != null)
{
updatedAdmin.City = admin.City;
updatedAdmin.Role = admin.Role;
ent.SaveChanges();
}
}
return true;
Related
Just as stated above, I am not sure how to call an API.
I have done it using fetch in the example below:
fetch("https://localhost:5001/api/patients/add", {
method: "POST",
mode: "cors",
cache: "no-cache",
headers: { "Content-Type": "application/json" },
body: postBody
});}
But it seems there is a different way of doing things in Razor view.
Below is what I have in my API:
// GET: api/Patients/5
[HttpGet("{id}")]
public async Task<ActionResult<Patient>> GetPatient(int id)
{
var patient = await _context.Patient.FindAsync(id);
if (patient == null)
{
return NotFound();
}
return patient;
}
It's just the GET made when creating an API in Visual Studio.
The following ajax call, within a script tag inside the razor page - although this is not best practice - would work as follows:
$.ajax({
type: "GET",
url: "#Url.Action("GetPatient", "Patients")",
data: { id : 1234 },
success: function(result){
//do something with result here
alert(result);
}
});
The second parameter of Url.Action is the Controller Name. This may need to be adapted for yourself.
This is what I ended up doing that worked. Thanks for the help guys!
$(document).ready(function () {
var options = {};
options.url = "https://localhost:44381/api/States";
options.type = "GET";
options.dataType = "json";
options.success = function (states) {
states.forEach(function (state) {
$("#state").append("<option>" + state.stateName + "</option>"
)
});
};
options.error = function () {
$("#msg").html("Error while calling the Web API!");
};
$.ajax(options);
});
I am trying to post a string (the name of the href the user clicked on) using AJAX to my MVC controller (which it will then use to filter my table results according to the string).
Whilst I have managed to get it to post (at-least according to the alerts) on the AJAX side, it doesn't seem to arrive properly on the controller side and is seen as null in my quick error capture (the if statement).
Please excuse the useless naming conventions for the moment. I've been going through countless methods to try and fix this, so will name properly when I've got a proper solution :).
I've been at work for this for a long while now and can't seem to solve the conundrum so any help is appreciated please! I'm very new to AJAX and MVC in general so I'm hoping it's a minor mistake. :) (FYI I have tried both post and get and both seem to yield the same result?)
Controller:
[Authorize]
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
using (CBREntities2 dc = new CBREntities2())
{
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
var safeItem = dc.Items.Where(a => a.Safe_ID == yarp).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
AJAX function (on View page):
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var yarp = $(this).attr('safesel');
var selectedSafeZZ = JSON.stringify("SEC-1000");
$.ajax({
url: '/Home/GetSafeItems',
data: { 'yarp': JSON.stringify(yarp) },
type: "GET",
success: function (data) {
alert(yarp);
console.log("We WIN " + data)
},
error: function (xhr) {
alert("Boohooo");
}
});
})
** The Alert reveals the correct type: "SEC-1000"
But the console Log shows: WE WIN [Object object]??
I have tried something basic in a new mvc dummy project :
View page basic textbox and a button :
<input type="text" id="txt_test" value="test"/>
<button type="button" class="btn" onclick="test()">Test</button>
<script type="text/javascript">
function test()
{
var text = $("#txt_test")[0].value;
$.ajax({
url: '#Url.RouteUrl(new{ action="GetSafeItems", controller="Home"})',
// edit
// data: {yarp: JSON.stringify(text)},
data: {yarp: text},
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
// edit
// alert(JSON.stringify(data));
alert(data.data);
}});
}
</script>
Controller :
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
return Json(new {data = string.Format("Back end return : {0}",yarp)}
, JsonRequestBehavior.AllowGet);
}
Alert result => {"data":"Back end return : \"test\""}
It's a simple ajax call to a web method. You don't return a view, so I don't understand the use of
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
Also I see an [Authorize] attribute, you perhaps use some authentication and I don't see any authentication header on your ajax call
Try this:
$.each(data, function (i) { console.log("We WIN " + data[i].Serial_Number )});
I'm building an app in C# (which is a little rusty) and I'm using an AJAX call to return some data from my database. I want to add some filtering to this by passing an object to the controller.
I've got it working when just one filter is used but I'm struggling when it comes to multiple filters. How do I set this up so I can check to see if that filter is being used and then filter the database on it?
This is my current code:
JS:
dataObj = new Object;
if (FormData) {
$.each(FormData, function (index, item) {
dataObj[item.name] = item.value;
});
};
$.ajax({
url: '#Url.Action("GetCompanies")',
data: dataObj,
type: 'GET',
dataType: 'json',
success: function (result) {
//Do stuff with data
}
});
Controller:
public JsonResult GetCompanies(SearchFilter SearchFilters)
{
if (!String.IsNullOrEmpty(SearchFilters.CustomerType) && SearchFilters.CustomerType != "All")
{
var data = _db.Customers.Where(a => a.Type.Contains(SearchFilters.CustomerType)).ToList();
var jsonData = Json(data, JsonRequestBehavior.AllowGet);
return jsonData;
}
else
{
var data = _db.Customers.ToList();
var jsonData = Json(data, JsonRequestBehavior.AllowGet);
return jsonData;
}
}
Thanks in advance!
I am trying to update my database when a checkbox is checked or unchecked. I want it to update when the checkbox is clicked. This is what I have so far, but my controller is never being hit. what can I do to fix it? Ideally I want to pass in the new value of customer.IsDone and customer.Id to my controller but I don't know how to do this.
Checkbox in my view
<td>#Html.CheckBoxFor(m => customer.IsDone, new { onclick = "UpdateCustomer(IsDone)" })</td>
The function in my view
function UpdateCustomer(isDone) {
$.ajax({
type: 'POST',
url: #Url.Action("UpdateCustomer", "Home"),
data: { check: isDone },
success: success,
dataType: 'json'
});
}
this is my controller method
[HttpPost]
public ActionResult UpdateCustomer(bool check)
{
//code will be here to update the db
var customers = new CustomerGetAll();
var list = customers.Execute();
return View("Customers", list);
}
I see few issues in your code.
First of all, you are passing IsDone variable when calling the UpdateCustomer method. But where is isDone defined ?
Second, this line,
url: #Url.Action("UpdateCustomer", "Home"),
The Url.Action helper will output a string and your code will be like this when rendered in the browser
url: /Home/UpdateCustomer,
Now the browser's javascript framework usually thinks the second part after : as a js variable and if you have not defined it,it will throw a syntax error about using a not defined variable! But since we have \, you will get another "Invalid regular expression flags" syntax error!
You should wrap the result in quotes to avoid this problem.
The below code should work
#Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)" })
and the script
function UpdateCustomer(elem) {
var isDone = $(elem).is(':checked');
$.ajax({
type: 'POST',
url: "#Url.Action("UpdateCustomer", "Home")",
data: { check: isDone },
success: function(res) {
console.log(res);
},
dataType: 'json'
});
}
Also, If you want to update a specific customer record, you probably want to pass the customer Id as well when making the ajax call. You may keep that in html 5 data attribute on the checkbox markup and read that and use that as needed.
#Html.CheckBoxFor(m =>customer.IsDone, new { onclick = "UpdateCustomer(this)",
data_customerid = customer.Id })
This will render the checkbox with html5 data attribute for "data-customerid". All you have to now do is, read this value and send it via ajax
function UpdateCustomer(elem) {
var isDone = $(elem).is(':checked');
var cid = $(elem).data('customerid');
$.ajax({
type: 'POST',
url: '#Url.Action("UpdateCustomer", "Home")',
data: { check: isDone,customerId:cid },
success: function(res) {
console.log(res);
}
});
}
Make sure your server action method has a new parameter to accept the customer id we are sending from client side code
[HttpPost]
public ActionResult UpdateCustomer(bool check,int customerId)
{
// to do : Save and return something
}
I have something similar, and I think you can solve your problem...
My HTML
<td>
#{
bool avalia1 = false;
#Html.CheckBox("avalia1", avalia1, new { autocomplete = "off", data_on_text = "Sim", data_off_text = "Não" })
}
</td>
JS
var avalia1 = $("#avalia1").is(":checked");
var url = "/Telefonia/GravarAvaliacao";
$.ajax({
url: url,
datatype: "json",
data: { 'avalia1': avalia1,'idgravacao': idgravacao },
type: "POST",
success: function (data) {
}
});
}
ON CONTROLLER
public JsonResult GravarAvaliacao(bool avalia1, string idgravacao)
{
string _userId = User.Identity.GetUserId();
var avaliaData = new OperadorAvaliacaoData();
avaliaData.GravaAvaliacao(avalia1, idgravacao);
return Json(true, JsonRequestBehavior.AllowGet);
}
The only diference is your model checkbox, and the action trigger.
I'm new to updating Enity Framework objects using JQuery and JSON. I created the entity objet in a console app and the update function and it works. I tried tranfering over to my web app and I can't get it to update through my web app.
Controller Code
[HttpPost]
public ActionResult Update(int rowID)
{
var keyValues = new KeyValuePair<string, object>[] {
new KeyValuePair<string, object>("QUICKFIX_ID", rowID)
};
var key = new EntityKey("CSCEntities.tbl_Quickfix_Toolbar", keyValues);
var quickfixtbl = (tbl_Quickfix_Toolbar)db.GetObjectByKey(key);
int usrcount = (int)quickfixtbl.USECOUNT_NR;
// update
usrcount = usrcount + 1;
// find the row to update using the ID
tbl_Quickfix_Toolbar quickFix = (from x in db.tbl_Quickfix_Toolbar
where x.QUICKFIX_ID == rowID
select x).First();
quickFix.USECOUNT_NR = usrcount;
db.SaveChanges();
return View();
}
and here is the JQueryfunction that calls my controller:
//Updates the use count in the List
function Update() {
$.ajax({
url: "/csc/devapp1/Home/Update",
type: 'POST',
data: "rowID=" +id,
contentType: "application/json;charset=utf-8",
success: function (data) {
alert('Details Updated Successfully');
},
error: function () {
alert('Unable to Update for the Given ID');
}
});
Please let me know what I'm doing wrong, I been going at this for weeks and can't get it to work.
change this line:
data: "rowID=" +id,
to this:
data: JSON.stringify({ rowID : id }),
And probably your URL is wrong:
change this:
url: "/csc/devapp1/Hom/Update/",
to this:
url: '/Home/Update',
And it should work